Skip to content

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

  1. Create Open API definitions (URL/code/template)
  2. Fill in authentication settings with the required credentials for securitySchemes
  3. Then call it in the env="server" script of Code/Layout/Page

Difference from k.net.httpClient

APIPurpose
k.openApiCall according to OpenAPI operation, automatically spell URL/authentication/caching
k.net.httpClientHandwritten 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 OpenAPI OperationType)

Example: GET /petspets_Get; POST /petspets_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:

LocationParameter nameType
Request bodybodyObject generated by schema, or any
Queryquery{operationId}_query object of shape
pathpath{operationId}_path object of shape
Request headerheader{operationId}_header
Cookiescookie{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:

sceneCommon fields
HTTP Basicusername, password
Bearer/API KeyaccessToken, name
OAuth2clientId, clientSecret, accessToken, refreshToken, expiresIn
ParameterTypeRequiredDescription
namestringYesAuthorization configuration name.
securityKeystringYesKey name from OpenAPI securitySchemes.
dataobjectYesCredential 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.

ParameterTypeRequiredDescription
namestringYesAuthorization 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

  1. Load OpenAPI documentation and authorization from site cache.
  2. Merge Base URL / servers to get the requested absolute address.
  3. Application security (Basic, Bearer, API Key, OAuth2, etc.).
  4. Optionally execute a custom authentication script.
  5. Populate path/query/header/cookie and send HTTP request.
  6. 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.