Updated on 2024-04-03 GMT+08:00

Creating an API

Scenario

You can selectively expose your services by configuring their APIs in APIG.

To create an API, set the basic information and define the API request, backend service, and responses.

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 during API creation.
  • If the backend service of the API is deployed in a VPC, you have created a VPC channel to access the service by following the procedure in Creating a VPC Channel. You can also create a VPC channel during API creation.

Setting Basic Information

  1. Access the shared gateway console.
  2. In the navigation pane, choose API Publishing > APIs.
  3. Click Create API, and set the parameters listed in Table 1.

    Table 1 Basic information

    Parameter

    Description

    Name

    API name. It is recommended that you enter a name based on naming rules to facilitate search.

    API Group

    The group to which the API belongs.

    If no API group is available, click Create API Group to create one.

    Gateway Response

    Displayed if APIG fails to process an API request.

    APIG provides a set of default responses and also allows you to create gateway responses with custom status codes and content, on the API Groups page. The response content must be in JSON format.

    Visibility

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

    • Public

    Security Authentication

    The following authentication modes are available:

    • App: Requests for the API will be authenticated by APIG.
    • 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.

    App authentication is recommended.

    NOTICE:
    • If you set the authentication mode of an API to IAM, 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 of an API to None, any user can access the API over public networks, which can result in excessive charges if the API is bombarded with malicious requests.
    • If you set the authentication mode of an API to Custom, you can create a function in FunctionGraph to interconnect with your own authentication system or service. This authentication mode is not supported in regions where FunctionGraph is unavailable.

    Simple Authentication

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

    If you select app authentication, you can 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 only supports HTTPS requests 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.

    Custom Authorizer

    This parameter is mandatory if Security Authentication is set to Custom.

    Select a custom authorizer if you set Security Authentication to Custom. If no custom authorizer is available, click Create Custom Authorizer to create one.

    Tag Name

    Classification attribute used to quickly identify the API from other APIs.

    Description

    Description of the API.

  4. Click Next.

Defining API Request

  1. On the Define API Request page, set the parameters listed in Table 2.

    Figure 1 Define API Request
    Table 2 Parameters for defining API requests

    Parameter

    Description

    Domain Name

    The subdomain automatically allocated to the API group.

    Protocol

    The protocol used for calling the API. Options:

    • HTTP
    • HTTPS
    • 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).

    Path

    The path for requesting the API.

    Enter a path in the format of "/users/{userId}/projects".

    • The variable in braces ({}) is a request parameter. Ensure that it is an entire segment between a pair of slashes (/). A segment that is not marked by a pair of slashes, for example, /abc{userId}, is not supported. If you set the matching mode to Exact match, you can add a plus sign (+) to the end of the request parameter, for example, /users/{p+}. The variable p matches the segments between one or multiple pairs of slashes (/).
    • Ensure that you define the parameters contained in the request path as input parameters.
    • The content is case-sensitive.

    Matching

    Options:

    • Exact match: The API can be called only using the specified request path.
    • Prefix match: The API can be called using paths starting with the matching characters.

      For example, if you set the request path to /test/AA and the matching mode to Prefix match, the API can be called using /test/AA/CC but cannot be called using /test/AACC.

    NOTE:
    • Exact match takes precedence over prefix match. Prefix match with a short prefix has a lower priority.

      For example, for request path /a/b/c (exact match), /a (prefix match), and /a/b (prefix match), the matching order is /a/b/c > /a/b > /a.

    • 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 service.

      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 service. The request URL received by the backend service is /test2/AA/CC/.

    Method

    The API calling method. The options are GET, POST, DELETE, PUT, PATCH, HEAD, OPTIONS, and ANY.

    • ANY indicates that the API can be called using any request method.
    • If you set Method to POST, PUT, PATCH, or ANY, set the request body.

    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 you enable CORS, you need to create another API that uses the OPTIONS method. For details, see CORS.

    Body

    Available for Method set to POST, PUT, PATCH, or ANY.

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

  2. (Optional) Set input parameters.

    Input parameters are transmitted together with the request when the API is called.
    1. Click Add Input Parameter.
    2. Set the parameters listed in Table 3.
      Table 3 Input parameter definition

      Parameter

      Description

      Name

      Name of the input parameter. If you set the parameter location to PATH, ensure that the parameter name is the same as that defined in the request path.

      NOTE:
      • The parameter name is not case-sensitive. 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 (_).

      Location

      Position of the parameter in requests. The options are PATH, HEADER, and QUERY.

      NOTE:

      If you set the parameter location to PATH, you must include the parameter in the request path.

      Type

      Type of the parameter value. Options: STRING and NUMBER.

      NOTE:

      Set the type of Boolean parameters to STRING.

      Mandatory

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

      Passthrough

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

      Default Value

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

      Enumerated Value

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

      Minimum Length

      The minimum length of the parameter value. Only numbers are allowed.

      Maximum Length

      The maximum length of the parameter value. Only numbers are allowed.

      Example

      Example value for the parameter.

      Description

      Description of the parameter.

    3. Click OK.

  3. Click Next.

Defining Backend Service

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 Define Backend Request page, select a backend type.

    Table 4, Table 5, and Table 6 describe the backend service parameters.

    Table 4 Parameters for defining an HTTP/HTTPS backend service

    Parameter

    Description

    Protocol

    HTTP or HTTPS. This protocol must be the one used by the backend service.

    NOTE:
    • APIG supports WebSocket data transmission. HTTP is equivalent to WebSocket (ws), and HTTPS is equivalent to WebSocket Secure (wss).
    • HTTPS is recommended for transmitting important or sensitive data.

    Method

    The API calling method. The options are GET, POST, DELETE, PUT, PATCH, HEAD, OPTIONS, and ANY.

    ANY indicates that the API can be called using any request method.

    VPC Channel

    Determine whether the backend service will be accessed using a VPC channel.

    • If yes, select a VPC channel.

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

    • If no, configure the backend service address.

      Enter a backend address in the format of "backend service IP address or domain name":"port number". The default port (80 for HTTP and 443 for HTTPS) will be used if no port is specified.

      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#.

    Host Header (if applicable)

    This parameter is available only if you set VPC Channel to Configure.

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

    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#.

    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.

    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

    FunctionURN

    Identifier of the requested function.

    Click Select Function URN to specify a function URN.

    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: synchronous invocation. 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: asynchronous invocation. 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)

    Backend request timeout. For details, see 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

    HTTP status code for API response. If your gateway does not support status codes, contact technical support to upgrade it.

    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.

    Header Parameters

    API response headers.

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

    • If you have defined an environment variable in the backend request path, the API cannot be debugged on the API debugging page.
    • For variables defined in the backend request path of an API, corresponding environment variables and their values must be configured. Otherwise, the API cannot be published because there will be no values that can be assigned to the variables.
    • Environment variable names are case-sensitive.

  2. (Optional) Add a backend policy.

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

    1. Click Add Backend Policy.
    2. Set parameters by referring to Table 7 and Table 4.
      Figure 2 Adding a backend policy
      Table 7 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 8.

      Table 8 Policy conditions

      Parameter

      Description

      Source

      • Source IP address
      • Input parameter
      NOTICE:

      Input parameters (for example, headers) set as policy conditions must have already been defined in the API request settings.

      Parameter Name

      • When setting Source to Input parameter, select an input parameter.

      Parameter Location

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

      Condition Type

      This parameter is required only if you set Source to Input parameter.

      • 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.

      Condition Value

      Set a condition value according to the condition type.
      • Equal: Enter a value.
      • Enumerated: Enter multiple values and separate them using commas.
      • Matching: Enter a range, for example, [0-5].

      If you have set Source to Source IP address, enter one or more IP addresses and separate them using commas.

  3. (Optional) Set backend parameters.

    Input parameters of the API are mapped to corresponding backend parameters in backend requests.

    1. Click next to Backend Parameters, and define backend parameters. You can use one of the following methods:
      • Click Import Input Parameter. All the defined input parameters are automatically displayed.
      • Click Add Backend Parameter Mapping, and add required backend parameters.
    2. Modify the mappings based on the parameters and their locations in backend requests. Figure 3 highlights the backend parameters.
      Figure 3 Backend service parameters
      1. If you set the parameter location to PATH, ensure that the parameter name is the same as that defined in the backend request path.
      2. The name and location of an input parameter can be different from those of the mapped backend request parameter.
        • The parameter name is not case-sensitive. 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 contain underscores (_).
      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.

        For example, test01 is abc, test02 is def, and test03 is xyz.

        API request:

        curl -ik -H 'test02:def' -X GET https://www.example01.com/v1.0/abc?test03=xyz

        Backend request:

        curl -ik -H 'test01:abc' -H 'test03:xyz' -X GET https://www.example02.com/v1.0/def

  4. (Optional) Set constant parameters.

    You can define constant parameters for the backend service to receive constants that are invisible to API callers. APIG adds constant parameters to specified positions in the request sent to the backend service.

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

    1. Click next to Constant Parameters.
    2. Click Add Constant Parameter, and set the parameters listed in Table 9.
      Figure 4 Adding constant parameters
      Table 9 Setting constant parameters

      Parameter

      Description

      Name

      Constant parameter name. If you set the parameter location to PATH, ensure that the parameter name is the same as that defined in the backend request path.

      NOTE:
      • The parameter name is not case-sensitive. 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 contain underscores (_).

      Location

      Position of the parameter in requests.

      The options are PATH, QUERY, and HEADER.

      Value

      Value of the parameter.

      Description

      Description of the constant parameter.

      • APIG sends requests containing constant parameters to backend services after percent-encoding of special parameter values. Ensure that the backend services support percent-encoding. For example, parameter value [apig] becomes %5Bapig%5D after percent-encoding.
      • For values of path parameters, the following characters will be percent-encoded: ASCII codes 0–31, blank symbols, ASCII codes 127–255, and special characters ?></%#"[\]^`{|}
      • For values of query strings, the following characters will be percent-encoded: ASCII codes 0–31, blank symbols, ASCII codes 127–255, and special characters >=<+&%#"[\]^`{|}

  5. (Optional) Set system parameters.

    System parameters refer to runtime parameters regarding gateway running and frontend and backend authentications. The parameters are transferred to the API backend service for access control and custom authentication.
    1. Click next to System Parameters.
    2. Click Add System Parameter, and set the parameters listed in Table 10.
      Figure 5 Adding a system parameter
      Table 10 System parameters

      Parameter

      Description

      System Parameter Type

      • Default gateway parameter: Default parameters supported by APIG.
      • Frontend authentication parameter: Parameters to be displayed in the frontend custom authentication result. This option is available only if you select Custom for Security Authentication on the Set Basic Information page.
      • Backend authentication parameter: Parameters to be displayed in the backend custom authentication result. This option is available only if you enable Backend Authentication on the Define Backend Request page.

      System Parameter Name

      • If System Parameter Type is Default gateway parameter, select any of the following parameters.
        • sourceIp: source IP address of the 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: app ID of the API provider
      • Ensure that the frontend and backend authentication parameters are consistent with the return result parameters defined for the corresponding custom authorizer function.

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

      Backend Parameter Name

      Name of the backend parameter to which the system parameter will be mapped.

      NOTE:
      • The parameter name is not case-sensitive. 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 contain underscores (_).

      Backend Parameter Location

      Position of the backend parameter in requests.

      Description

      Description of the system parameter.

  6. Click Next.

Defining Responses

  1. On the Define Response page, set the parameters listed in Table 11.

    Table 11 Defining responses

    Parameter

    Description

    Example Success Response

    An example of a response returned when the API is called successfully.

    Example Failure Response

    An example of a response returned when the API fails to be called.

  2. Click Finish.

    After the API is created, click its name in the API list to view details.

Follow-Up Operations

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