Appearance
k.openApi
Call external HTTP API according to site OpenAPI definition and manage authentication credentials
Overview
k.openApi is Kooboo's script encapsulation of the Swagger/OpenAPI specification imported in Develop → Open API. Each definition has a unique name in the background (such as petstore), corresponding to:
text
k.openApi.{name}.{operation}(params...)
k.openApi.{name}.authorize.{method}(...)After saving the Open API definition, Kooboo will parse jsonData and generate TypeScript types and completions (OpenApi namespace) for the current site. Operation names and parameters vary from specification to specification. The general rules are explained below; the specific name is subject to the IDE prompt or background definition.
configure the background first
- Create Open API definitions (URL/code/template)
- Fill in authentication settings with the required credentials for
securitySchemes - Then call it in the
env="server"script of Code/Layout/Page
Difference from k.net.httpClient
| API | Purpose |
|---|---|
k.openApi | Call according to OpenAPI operation, automatically spell URL/authentication/caching |
k.net.httpClient | Handwritten HTTP request for arbitrary URL |
The API documentation (Code Swagger) exposed by this site can be found in code resources and /_api/v2/codeOpenApi/document, not k.openApi.
access structure
text
k.openApi
└── {openApiName} // Admin "Name"
├── authorize // Credential management (KAuthorize)
├── {operationId} // One callable function per path + method
└── ... // Model types from the spec (OpenApi.*)Operation Name
Generated by path + HTTP method in the specification, the rules are:
text
{normalizedPath}_{Method}- Path: Non-alphanumeric characters are replaced with
_, and if they start with a number, add the prefix_(such as/pet/{petId}→_pet__petId_) - Method:
Get,Post,Put,Delete,Patch, etc. (consistent with OpenAPIOperationType)
Example: GET /pets → pets_Get; POST /pets → pets_Post (subject to actual generation, please refer to IDE completion).
Call parameters
The order of function parameters for each operation is consistent with the OpenAPI parameter position:
| Location | Parameter name | Type |
|---|---|---|
| Request body | body | Object generated by schema, or any |
| Query | query | {operationId}_query object of shape |
| path | path | {operationId}_path object of shape |
| Request header | header | {operationId}_header |
| Cookies | cookie | {operationId}_cookie |
Only pass the required objects; unused ones can be omitted.
ts
k.api.get(() => {
// Operation names follow IDE completion, for example GET /items -> items_Get
const page = k.openApi.myService.items_Get({
query: { limit: 10 },
})
return page
})Authentication and default authorize
If the operation declares security, the corresponding authorization record must exist before the call (backend or script writing). If not specified, the first authorization name under this Open API is used.
Throws Api not authorize to indicate missing or incorrect securitySchemes credentials.
Custom authentication
When Custom Authentication is enabled in the background, the KScript in the configuration will be executed before the request is issued, and the injected request.headers, request.querys, etc. can be modified (see Open APIs (CMS)).
response cache
When the cache configured for a certain method + path mode hits in the background, the last result in the memory (key including URL and authorize name) is directly returned without requesting the remote end again.
Array query parameters
When Use comma array is checked on the definition, the array in the query will be serialized as a=1,2,3; otherwise, it will be a duplicate key a=1&a=2.
authorize
k.openApi.{name}.authorize manages multiple sets of credentials under this definition (corresponding to the background authentication settings).
list()
Returns an array of all authorizeName strings.
Parameters: none.
Returns: string[]. Authorization names under the current Open API definition.
ts
const names = k.openApi.myService.authorize.list()addOrUpdate(name, securityKey, data)
Write or update a set of credentials. securityKey is the key name of securitySchemes in the specification (illegal characters will be standardized as _ in lower case). The data field depends on the scheme type, for example:
| scene | Common fields |
|---|---|
| HTTP Basic | username, password |
| Bearer/API Key | accessToken, name |
| OAuth2 | clientId, clientSecret, accessToken, refreshToken, expiresIn |
| Parameter | Type | Required | Description |
|---|---|---|---|
name | string | Yes | Authorization configuration name. |
securityKey | string | Yes | Key name from OpenAPI securitySchemes. |
data | object | Yes | Credential data. Fields depend on the security scheme type. |
Returns: void.
ts
k.openApi.myService.authorize.addOrUpdate("sandbox", "bearer_auth", {
accessToken: "xxx",
name: "Bearer",
})addOrUpdate_{securityKey}(name, data)
Convenience method for splitting by security scheme (equivalent to addOrUpdate, specific suffix visible in the IDE).
ts
k.openApi.myService.authorize.addOrUpdate_bearer_auth("sandbox", {
accessToken: "xxx",
})delete(name)
Delete the authorization configuration named name.
| Parameter | Type | Required | Description |
|---|---|---|---|
name | string | Yes | Authorization configuration name to delete. |
Returns: void.
ts
k.openApi.myService.authorize.delete("sandbox")getAuthorizationUrl_{securityKey}(name, clientId, clientSecret)
OAuth2 authorizationCode flow: Generate authorization page URL (and stash clientId/secret). Template example:
html
<script env="server">
var url = k.openApi.myService.authorize.getAuthorizationUrl_oauth2(
"admin",
"client-id",
"client-secret"
)
</script>
<a k-attribute="href {url}" target="_blank">Authorize</a>The callback URL is in the form: {scheme}://{host}/_api/openapioauth2callback/{siteId}/{authorizeId}/{securityKey}.
Runtime behavior summary
- Load OpenAPI documentation and authorization from site cache.
- Merge
Base URL/serversto get the requested absolute address. - Application
security(Basic, Bearer, API Key, OAuth2, etc.). - Optionally execute a custom authentication script.
- Populate path/query/header/cookie and send HTTP request.
- Parse the response (mostly JSON) by Content-Type and return a JavaScript object.
TypeScript and IDE
Each Open API name will generate interfaces under the OpenApi namespace and method signatures on k.openApi.{name}. Refresh the type cache after resaving the definition to update the completion.
Security-related data models are generated with the OpenAPI definition, for example Token, OAuth2, and HttpBasic.
Related Docs
- Open API(CMS) — Import specification, cache, background authorization
- k.net.httpClient — Generic HTTP
- k.security — JWT, hashes, etc.
- Authentication (CMS) — Inbound request authentication (non-external API)