Updated on 2024-08-07 GMT+08:00

Creating an API

You can selectively expose your backends by configuring their APIs in APIG. To create an API, perform the following steps:

APIG uses a REST-based API architecture, so API opening and calling must comply with related RESTful API specifications.

Prerequisites

  • You have created an API group. If no API group is available, create one by referring to Creating an API Group.
  • If the backend service needs to use a load balance channel, create a channel first.
  • If you need to use a custom authorizer for API authentication, create one.

Configuring Frontend Settings

  1. Go to the APIG console.
  2. Select a dedicated gateway at the top of the navigation pane.
  1. Choose API Management > API Groups.
  2. Click a group name.
  3. On the APIs tab, click Create API.

    1. Configure the frontend parameters described in the following table.

      The new API must have a different group, request method, request path, and matching mode from those of any existing API.

      Table 1 Frontend definition

      Parameter

      Description

      API Name

      Enter an API name that conforms to specific rules to facilitate search.

      Group

      The group to which the API belongs.

      URL

      Frontend address, which consists of a method, protocol, subdomain name, and path.

      • Method: Select GET, POST, DELETE, PUT, PATCH, HEAD, OPTIONS, or ANY. ANY indicates that the API can be called using any method.
      • Protocol: Select HTTP, HTTPS, or HTTP&HTTPS. HTTPS is recommended for transmitting important or sensitive data.

        APIG supports WebSocket data transmission. HTTP is equivalent to WebSocket (ws), and HTTPS is equivalent to WebSocket Secure (wss).

      • Subdomain Name: Debugging domain name of the group to which the API belongs.
      • Path: Request path of the API. Enclose parameters in braces, if any. For example: /a/{b}. Alternatively, use a plus sign (+) to match paths starting with specific characters. For example: /a/{b+}. The request path is case-sensitive.

      Gateway Response

      Displayed if an API request fails to be processed.

      APIG provides a set of default responses and also allows you to create new ones with custom status codes and content on the Group Information page. The response content must be in JSON format.

      Matching

      Matching mode of the API request path.

      • Exact match: The path in a request for the API must be the same as the value of Path.
      • Prefix match: The path in a request for the API must be prefixed with the value of Path. You can define multiple paths in this mode.

        For example, if you set Path to /test/AA and Matching to Prefix match, the API can be called using /test/AA/BB and /test/AA/CC but cannot be called using /test/AACC.

      NOTE:
      • If you set the matching mode to Prefix match, the characters of the API request path excluding the prefix are transparently transmitted to the backend.

        For example, if you define the frontend and backend request paths of an API as /test/ and /test2/, respectively, and the API is called using /test/AA/CC, the characters AA/CC will be transparently transmitted to the backend. The request URL received by the backend is /test2/AA/CC/.

      • In prefix match mode, the path in a request preferentially matches the API with the longest path.

        For example, assume that prefix match is enabled for two APIs whose paths are /test/AA and /test/AA/BB, respectively. The path /test/AA/BB/c in a request matches the API whose path is /test/AA/BB.

      • If there are two APIs with the same group, request method, and request path, the API with exact matching is first called.

      Tags

      Attributes used to quickly identify the API from other APIs.

      Description

      Description of the API.

      Request Body Format

      Enable the parameter to specify a format for API requests. APIG will transmit API requests to the backend by using the selected format. The options include application/json, application/xml, text/plain, and multipart/form-data. The selected format must be supported by the backend service.

      Request Body Content

      Enter the content of the request body in the API request to help API callers understand how to correctly encapsulate API requests.

    2. Configure security settings based on the following table.
      Table 2 Security configuration

      Parameter

      Description

      Visibility

      Determine whether the API is available to the public. Options:

      • Public: The API can be released on KooGallery.
      • Private: The API will be excluded when the API group to which it belongs is released on KooGallery.

      Authentication Mode

      The following authentication modes are available:

      • App: Requests for the API will be authenticated by APIG. App authentication is recommended.
      • IAM: Requests for the API will be authenticated by Identity and Access Management (IAM).
      • Custom: Requests for the API will be authenticated by using your own authentication system or service (for example, an OAuth-based authentication system).
      • None: No authentication will be required.

      API calling varies depending on the authentication mode. For details, see Calling APIs.

      NOTICE:
      • If you set the authentication mode to IAM or None, any APIG user can access the API, which can result in excessive charges if the API is bombarded with malicious requests.
      • If you set the authentication mode to Custom, you can create a function in FunctionGraph to interconnect with your own authentication system or service. Ensure that FunctionGraph is available in the current region.

      Simple Authentication

      This parameter is available only if you set Security Authentication to App.

      If you select app authentication, configure whether to enable simple authentication. In simple authentication, the X-Apig-AppCode parameter is added to the HTTP request header for quick response. APIG verifies only the AppCode and the request content does not need to be signed.

      Simple authentication supports HTTPSrequests and does not support HTTP requests. For details, see Adding an AppCode for Simple Authentication.

      NOTE:

      After you enable simple authentication for an existing API, you need to publish the API again. For details, see Publishing an API.

      Two-Factor Authentication

      This parameter is available only if Authentication Mode is set to App or IAM.

      Determine whether to enable two-factor authentication for the API. If this option is enabled, API requests will be authenticated using a custom authorizer in addition to the app or IAM authentication you specify.

      Custom Authorizer

      This parameter is mandatory only if Authentication Mode is set to Custom.

      If no custom authorizer is available, click Create Custom Authorizer to create one.

      CORS

      Determine whether to enable cross-origin resource sharing (CORS).

      CORS allows browsers to send XMLHttpRequest to servers in other domains, overcoming the limitation that Asynchronous JavaScript and XML (AJAX) can be used only within the same domain.

      There are two types of CORS requests:

      • Simple requests: requests that have the Origin field in the header.
      • Not-so-simple requests: HTTP requests sent before the actual request.

      If CORS (not-so-simple request) is enabled for an API, another API that uses the OPTIONS method must be created. For details, see Enabling CORS.

    3. (Optional) Define request parameters described in the following table.
      Table 3 Request parameter configuration

      Parameter

      Description

      Parameter Name

      Request parameter name. The name of a path parameter will be automatically displayed in this column.

      NOTE:
      • The parameter name is case-insensitive. It cannot start with x-apig- or x-sdk-.
      • The parameter name cannot be x-stage.
      • If you set the parameter location to HEADER, ensure that the parameter name is not Authorization or X-Auth-Token and does not contain underscores (_).

      Parameter Type

      Options: STRING and NUMBER.

      NOTE:

      Set the type of Boolean parameters to STRING.

      Required

      Determine whether the parameter is required in each request sent to call the API. If you select Yes, API requests that do not contain the parameter will be rejected.

      Passthrough

      Determine whether to transparently transmit the parameter to the backend service.

      Enumerated Value

      Enumerated value of the parameter. Use commas (,) to separate multiple enumerated values. The value of this parameter can only be one of the enumerated values.

      Default Value

      The value that will be used if no value is specified for the parameter when the API is called. If the parameter is not specified in a request, APIG automatically sends the default value to the backend service.

      Value Restrictions

      • Max. length/Max. value: If Parameter Type is set to STRING, set the maximum length of the parameter value. If Parameter Type is set to NUMBER, set the maximum parameter value.
      • Min. length/Min. value: If Parameter Type is set to STRING, set the minimum length of the parameter value. If Parameter Type is set to NUMBER, set the minimum parameter value.

      Example

      Example value for the parameter.

      Description

      Description of the parameter.

  4. Click Next to proceed with Configuring Backend Settings.

Configuring Backend Settings

APIG allows you to define multiple backend policies for different scenarios. Requests that meet specified conditions will be forwarded to the corresponding backend. For example, you can have certain requests to an API forwarded to a specific backend by specifying the source IP address in the policy conditions of the backend.

You can define a maximum of five backend policies for an API in addition to the default backend.

  1. Define the default backend.

    API requests that do not meet the conditions of any backend will be forwarded to the default backend.

    On the Backend Configuration page, select a backend type.

    APIG supports HTTP&HTTPS, FunctionGraph, and Mock backends. For details about the parameters required for defining each type of backend service, see Table 4, Table 5, and Table 6.

    • FunctionGraph backends can be set only if FunctionGraph has been deployed in the current environment.
    • If the backend service is unavailable, use the Mock mode to return the expected result to the API caller for debugging and verification.
    Table 4 Parameters for defining an HTTP&HTTPS backend service

    Parameter

    Description

    Load Balance Channel

    Determine whether to use a load balance channel to access the backend service. If you select Configure, ensure that you have created a load balance channel.

    URL

    A URL consists of a method, protocol, load balance channel/backend address, and path.

    • Method

      Select GET, POST, DELETE, PUT, PATCH, HEAD, OPTIONS, or ANY. ANY indicates that all request methods are supported.

    • Protocol

      HTTP or HTTPS. HTTPS is recommended for transmitting important or sensitive data.

      NOTE:
      • APIG supports WebSocket data transmission. HTTP is equivalent to WebSocket (ws), and HTTPS is equivalent to WebSocket Secure (wss).
      • This protocol must be the one used by the backend service.
    • Load Balance Channel (if applicable)

      Select a load balance channel.

      NOTE:

      To ensure a successful health check and service availability, configure the security groups of cloud servers in each channel to allow access from 100.125.0.0/16.

    • Backend Address (if applicable)

      Set this parameter if no load balance channel is used.

      Enter the access address of the backend service in the format of Host:Port. Host indicates the IP address or domain name for accessing the backend service. If no port is specified, port 80 is used for HTTP by default, and port 443 is used for HTTPS by default.

      To use environment variables in the backend address, enclose the variables with number signs (#), for example, #ipaddress#. You can use multiple environment variables, for example, #ipaddress##test#.

    • Path

      The request path (URI) of the backend service. Ensure that any parameters in the path are enclosed in braces ({}). For example, /getUserInfo/{userId}.

      If the path contains an environment variable, enclose the environment variable in number signs (#), for example, /#path#. You can use multiple environment variables, for example, /#path##request#.

    Host Header (if applicable)

    Set this parameter only if a load balance channel is used.

    Define a host header for requests to be sent to cloud servers associated with the load balance channel. By default, the original host header in each request is used.

    Timeout (ms)

    Backend request timeout. Range: 1–60,000 ms.

    If a backend timeout error occurs during API debugging, increase the timeout to locate the reason.

    NOTE:

    If the current timeout does not meet your service requirements, modify the maximum timeout by referring to Configuring Parameters. The value range is 1 ms to 600,000 ms. After modifying the maximum timeout, also modify the timeout here.

    Retries

    Number of attempts to retry requesting the backend service. Default: 0; range: –1 to 10.

    • If the value is –1, the retry function is disabled. However, requests except for those using POST and PATCH will be retried once by default.
    • If the value is within 0 to 10, the retry function is enabled, and requests will retry for the specified number of times. 0 indicates no retry attempts will be made.

    If a load balance channel is used, the number of retries must be less than the number of enabled backend servers in the channel.

    Two-Way Authentication

    Set this parameter only when Protocol is set to HTTPS.

    Determine whether to enable two-way authentication between APIG and the backend service. If you enable this option, configure the backend_client_certificate parameter on the Parameters page of the gateway.

    Backend Authentication

    Determine whether your backend service needs to authenticate API requests.

    If you enable this option, select a custom authorizer for backend authentication. Custom authorizers are functions that are created in FunctionGraph to implement an authentication logic or to invoke an authentication service.

    NOTE:

    Backend authentication relies on FunctionGraph and is only available in certain regions.

    Table 5 Parameters for defining a FunctionGraph backend service

    Parameter

    Description

    Function Name

    Automatically displayed when you select a function.

    Function URN

    Identifier of the function.

    Click Select to specify a function.

    Version/Alias

    Select a function version or alias. For details, see sections "Managing Versions" and "Managing Aliases" in the FunctionGraph User Guide.

    Invocation Mode

    • Synchronous: When receiving an invocation request, FunctionGraph immediately processes the request and returns a result. The client closes the connection once it has received a response from the backend.
    • Asynchronous: The function invocation results of client requests do not matter to clients. When it receives a request, FunctionGraph queues the request, returns a response, and then processes requests one by one in idle state.

    Timeout (ms)

    Timeout duration for APIG to request for the backend service. For details, see the description about backend timeout in Table 4.

    Backend Authentication

    For details, see the description about backend authentication in Table 4.

    Table 6 Parameters for defining a Mock backend service

    Parameter

    Description

    Status Code

    Select the HTTP status code to be returned by the API.

    Response

    You can use Mock for API development, debugging, and verification. It enables APIG to return a response without sending the request to the backend. This is useful if you need to test APIs when the backend is unavailable.

    Backend Authentication

    For details, see the description about backend authentication in Table 4.

    Add Header

    Customize the response header parameters for the API.

    Click Add Header, and enter the parameter name, value, and description.

    • APIs whose URLs contain variables cannot be debugged on the API debugging page.
    • For variables defined in URLs of APIs, corresponding environment variables and their values must be configured. Otherwise, the APIs cannot be published because there will be no values that can be assigned to the variables.
    • The variable name is case-sensitive.

  2. (Optional) Configure backend parameters to map them to the request parameters defined in corresponding locations. If no request parameter is defined in 5.c, skip this step.

    1. In the Backend Parameters area, add parameters in either of the following ways:
      • Click Import Request Parameter to synchronize all defined request parameters.
      • Click Add Backend Parameter Mapping to add a backend parameter.
    2. Modify mappings (see Figure 1) based on the parameters and their locations in backend requests.
      Figure 1 Configuring backend parameters
      1. If the parameter location is set to PATH, the parameter name must be the same as that defined in the backend request path.
      2. The name and location of a request parameter can be different from those of the mapped backend parameter.
        • The parameter name is case-insensitive. It cannot start with x-apig- or x-sdk-.
        • The parameter name cannot be x-stage.
        • If you set the parameter location to HEADER, ensure that the parameter name does not start with an underscore (_).
      3. In the preceding figure, parameters test01 and test03 are located in the path and query positions of API requests, and their values will be received in the header of backend requests. test02 is located in the header of API requests, and its value will be received through test05 in the path of backend requests.

        Assume that test01 is aaa, test02 is bbb, and test03 is ccc.

        The API request is as follows:

        curl -ik -H 'test02:bbb' -X GET https://example.com/v1.0/aaa?test03=ccc

        Backend request:

        curl -ik -H 'test01:aaa' -H 'test03:ccc' -X GET https://example.com/v1.0/bbb

  3. (Optional) Configure constant parameters for the default backend to receive constants that are invisible to API callers. When sending a request to the backend service, APIG adds these parameters to the specified locations in the request and then sends the request to the backend service.

    In the Constant Parameters area, click Add Constant Parameter.

    Constant parameters will be stored as plaintext. To prevent information leakage, do not contain sensitive information in these parameters.

    Table 7 Constant parameter configuration

    Parameter

    Description

    Constant Parameter Name

    If Parameter Location is set to PATH, the parameter name must be the same as that in Path.

    NOTE:
    • The parameter name is case-insensitive. It cannot be x-stage or start with x-apig- or x-sdk-
    • If Parameter Location is set to HEADER, the parameter name is case-insensitive and cannot start with an underscore (_).

    Parameter Location

    Specify the location of the constant parameter in backend service requests. The options include PATH, HEADER, and QUERY.

    Parameter Value

    Value of the constant parameter.

    Description

    Description about the constant parameter.

    • APIG sends requests containing constant parameters to a backend service after percent-encoding of special parameter values. Ensure that the backend service supports percent-encoding. For example, parameter value [api] becomes %5Bapi%5D after percent-encoding.
    • For values of path parameters, APIG percent-encodes the following characters: ASCII codes 0–31 and 127–255, spaces, and other special characters ?></%#"[\]^`{|}
    • For values of query strings, APIG percent-encodes the following characters: ASCII codes 0–31 and 127–255, spaces, and other special characters >=<+&%#"[\]^`{|}

  4. (Optional) Configure system parameters for the default backend to receive default gateway parameters, frontend authentication parameters, and backend authentication parameters. When sending a request to the backend service, APIG adds these parameters to the specified locations in the request and then sends the request to the backend service.

    1. In the System Parameters area, click Add System Parameter.
      Table 8 System parameter configuration

      Parameter

      Description

      System Parameter Type

      Options:

      • Default gateway parameter: Parameters supported by APIG.
      • Frontend authentication parameter: Parameters to be displayed in the frontend custom authentication result. This option is available only if you have set Authentication Mode to Custom in Configuring Frontend Settings.
      • Backend authentication parameter: Parameters to be displayed in the backend custom authentication result. This option is available only if you have enabled backend authentication in Configuring Backend Settings.

      System Parameter Name

      Name of the system parameter.

      • If System Parameter Type is Default gateway parameter, select any of the following parameters.
        • sourceIp: source IP address of an API caller
        • stage: environment in which the API is called
        • apiId: ID of the API
        • appId: ID of the app that calls the API
        • requestId: request ID generated when the API is called
        • serverAddr: IP address of the gateway server
        • serverName: name of the gateway server
        • handleTime: processing time of the API request
        • providerAppId: credential ID of the API provider
        • apiName: name of the API. This parameter is available only after the API is published.
        • appName: name of the credential used to call the API
      • If System Parameter Type is Frontend authentication parameter or Backend authentication parameter, enter a parameter that has been defined for custom authentication results.

      For details about how to create a custom authorizer function and obtain result parameters, see API Gateway Developer Guide.

      Backend Parameter Name

      Name of a backend parameter to map the system parameter.

      NOTE:
      • The parameter name is case-insensitive. It cannot be x-stage or start with x-apig- or x-sdk-
      • If Parameter Location is set to HEADER, the parameter name is case-insensitive and cannot start with an underscore (_).

      Backend Parameter Location

      Specify the location of the backend parameter in backend service requests. The options include PATH, HEADER, and QUERY.

      Description

      Description about the system parameter.

  5. (Optional) Add a backend policy.

    You can add backend policies to forward requests to different backend services.

    1. Click to add a backend policy.
    2. Set policy parameters described in Table 9. For details about other parameters, see Table 4, Table 5, and Table 6.
      Table 9 Backend policy parameters

      Parameter

      Description

      Name

      The backend policy name.

      Effective Mode

      • Any condition met: The backend policy takes effect if any of the policy conditions has been met.
      • All conditions met: The backend policy takes effect only when all the policy conditions have been met.

      Policy Conditions

      Conditions that must be met for the backend policy to take effect. Set conditions by referring to Table 10.

      Table 10 Policy condition configuration

      Parameter

      Description

      Source

      • Source IP address: IP address from which the API is called
      • Request parameter: a request parameter defined for the API
      • Cookie: cookies of an API request
      • System parameter - Default gateway parameter: a default gateway parameter used to define system runtime for the API
      NOTICE:
      • The request parameters (for example, headers) set as policy conditions must have already been defined for the API.
      • If System parameter is not displayed, contact technical support to upgrade the gateway.

      Parameter Name

      • When setting Source to Request parameter, select a request parameter.
      • When setting Source to System parameter, select a system parameter.
        • reqPath: Request URI, for example, /a/b/c.
        • reqMethod: Request method, for example, GET.
      • When setting Source to Cookie, enter the name of a cookie parameter.

      Parameter Location

      The parameter location is displayed only if you set Source to Request parameter.

      Condition Type

      This parameter is required only if you set Source to Request parameter, System parameter, or Cookie.

      • Equal: The request parameter must be equal to the specified value.
      • Enumerated: The request parameter must be equal to any of the enumerated values.
      • Matching: The request parameter must be equal to any value of the regular expression.
      NOTE:

      When you set Source to System parameter and select a parameter named reqMethod, you can set the condition type only to Equal or Enumerated.

      Condition Value

      • If Condition Type is Equal, enter a value.
      • If Condition Type is Enumerated, enter multiple values and separate them with commas (,).
      • If Condition Type is Matching, enter a value range, for example, [0-5].
      • If Source is Source IP address, enter one or more IP addresses and separate them with commas (,).

  6. Defining responses.

    In the Responses area, set the example responses.
    Table 11 Defining responses

    Parameter

    Description

    Example Success Response

    The response to be returned when the API is called successfully.

    Example Failure Response

    The response to be returned when the API fails to be called.

  7. Click Finish. You can view the API details on the APIs tab that is displayed.

(Optional) Creating a Policy

You can create policies for the API after publishing it.

  1. On the APIs tab, click Create Policy.
  2. Select a policy type and set parameters.

  3. Click OK.

Follow-Up Operations

After creating an API, verify it by following the procedure in Debugging an API.