All Products
Search
Document Center

API Gateway:Use Function Compute as the backend service of an API

Last Updated:Mar 09, 2023

Function Compute is an event-driven compute service. Functions in Function Compute are event-driven. When an event occurs, the event triggers the execution of the corresponding function. API Gateway is supported as an event source for Function Compute. After API Gateway receives a request for an API that uses Function Compute as the backend service, API Gateway triggers the execution of the corresponding function in Function Compute and Function Compute returns the execution result to API Gateway.

1. Overview

After API Gateway is integrated with Function Compute, Function Compute can be accessed by using API Gateway and features such as authentication, throttling, and data conversion are supported. For more information, see Features.

API Gateway supports the integration of HTTP functions and event functions. The following sections describe how to integrate the two types of functions with API Gateway.

2. Integrate HTTP functions with API Gateway

An HTTP function is a function for which an HTTP trigger is configured when the function is created in Function Compute. For information about how to configure an HTTP trigger, see Configure an HTTP trigger that invokes a function with HTTP requests.

2.1 Create an API

a. Log on to the API Gateway console. In the left-side navigation pane, choose OpenAPI > API Groups. Select a region in the top navigation bar and click Create Group. If an API group is created, skip this step.

Note

If the API group that you create does not reside in the same region as Function Compute, API Gateway accesses your service in Function Compute over the Internet. If you require high data security and low network latency, select the same region where Function Compute resides when you create the API group in API Gateway.

b. Create and configure the API. In the left-side navigation pane, click APIs. On the APIs page, click Create API and configure the parameters based on your business requirements. In the Define Backend Service step, set the Backend Service Type parameter to Function Compute.

Function Type: Select HTTP Function.

Trigger Path: Copy the path in the Triggers tab of the Function Details page in the Function Compute console.

If the API is called in the same region as Function Compute, you can replace the domain name on the trigger path to an internal endpoint. To find the internal endpoint, go to the Function Compute console and select Overview. Then, click Endpoint in the References section of the page.

Backend Request Path: Custom paths are supported. If you do not want to use a custom path, enter a forward slash (/) in the field.

HTTP Method: Select a method supported by Function Compute from the drop-down list. If multiple methods are supported, select ANY.

Role ARN: You must authorize API Gateway to access your service in Function Compute. API Gateway automatically obtains the ARN of a role. If you want to access the Function Compute service of another Alibaba Cloud account, you must enter the ARN of the role that is granted the required permissions. If you use a dedicated instance, you must upgrade the instance version to 3.5.3.721 or later. Click Next to go to the Define Response step. The configurations in this step can be used only to generate documents.

2.2 Publish an API

After you create an API, you can publish the API to the test environment or production environment and authorize an app to call the API. If the Caller Authentication is set to No Authentication, you do not need to authorize an app.

2.3 Debug an API

Log on to the API Gateway console and choose OpenAPI > APIs in the left-side navigation pane. On the APIs page, click the name of the API that you want to debug. On the page that appears, click Debug API in the left-side navigation pane to go to the debugging page.

In pass-through mode, users can configure the parameters that are required for API calls to debug an API.

3. Integrate event functions with API Gateway

3.1 Integrate event functions with API Gateway to create services

You can configure API Gateway to trigger function execution in the Function Compute console. For more information, see Configure an API Gateway trigger.

3.1.1 Create an API

The operations that are performed in this section to create an API group and an API in the API Gateway console are similar to the operations that are performed in the "2.1 Create an API" section of this topic. The only difference between the operations is the configurations in the Define Backend Service step. The following items describe the different configurations:

Function Type: Select Event Function

Region: Select the region where the Function Compute service resides. If the API group that you create does not reside in the same region as Function Compute, API Gateway accesses your service in Function Compute over the Internet. If you require high data security and low network latency, select the same region where Function Compute resides when you create the API group in API Gateway.

Service Name and Function Name: Configure the parameters based on the actual service name and function name in Function Compute.

image

3.1.2 Publish an API

After you create an API, you can publish the API to the test environment or production environment and authorize an app to call the API. If the Caller Authentication is set to No Authentication, you do not need to authorize an app.

3.1.3 Debug an API

Log on to the API Gateway console and choose OpenAPI > APIs in the left-side navigation pane. On the APIs page, click the name of the API that you want to debug. On the page that appears, click Debug API in the left-side navigation pane to go to the debugging page. In pass-through mode, users can configure the parameters that are required for API calls to debug an API.

3.2 Format requirements when an event function is integrated with API Gateway

After API Gateway receives a request for an API that uses an event function in Function Compute as the backend service, API Gateway converts the request parameters to key-value pairs in the map format and sends the request to Function Compute. Function Compute handles the request and returns a response in a specific output format to API Gateway. The response includes information such as the status code, headers, and body. The following figure shows the response details. API Gateway maps the information in the response that is returned by Function Compute to the status code, headers, and body of an API response, and returns the API response to the client.

Input format of request parameters in each API request that API Gateway sends to Function Compute

After API Gateway receives a request for an API that uses Function Compute as the backend service, API Gateway converts request parameters in the request to key-value pairs in the map format. Then, API Gateway passes the key-value pairs to Function Compute as the value of the event parameter to trigger the execution of the corresponding function. The following sample code provides an example on how Function Compute obtains the required parameters from the key-values pairs that are sent from API Gateway:

{
        "path":"api request path",
        "httpMethod":"request method name",
        "headers":{all headers,including system headers},
        "queryParameters":{query parameters},
        "pathParameters":{path parameters},
        "body":"string of request payload",
        "isBase64Encoded":"true|false, indicate if the body is Base64-encode"
}
  • If the value of isBase64Encoded is true, the body of the request sent from API Gateway to Function Compute is Base64-encoded. To trigger the corresponding function, Function Compute needs to perform Base64 decoding on the body.

  • If the value of isBase64Encoded is false, the body of the request sent from API Gateway to Function Compute is not Base64-encoded.

Output format of the response that Function Compute sends to API Gateway

The following example code provides an example on how Function Compute sends the execution result of the corresponding function to API Gateway in the JSON format. API Gateway then parses the response that is returned by Function Compute.

{
        "isBase64Encoded":true|false,
        "statusCode":httpStatusCode,
        "headers":{response headers},
        "body":"..."
}
  • If the body of the response is binary data, the body must be Base64-encoded by Function Compute. To enable body encoding, set isBase64Encoded to true in the response. If the body does not need to be Base64-encoded, set isBase64Encoded is false. If the value of isBase64Encoded is true in the response that is sent from Function Compute, API Gateway decodes the body before sending the response to the client.

  • In the Node.js environment, Function Compute constructs a callback parameter based on different execution results:

    • If the result that needs to be sent to API Gateway is a success response, the value of the callback parameter is in the following format: callback(null,{"statusCode":200,"body":"..."}).

    • If the result that needs to be sent to API Gateway is an exception, the value of the callback parameter is in the following format: callback(new Error('internal server error'),null).

    • If the result that needs to be sent to API Gateway is the response for an error that is caused by the client's request, the value of the callback parameter is in the following format: callback(null,{"statusCode":400,"body":"param error"}).

  • If Function Compute returns a response that is not in the required format, API Gateway returns the "503 Service Unavailable" error message to the client.

3.3 Examples on calling an event function

The following sections provide sample code on an event function, an API request, and an API response.

3.3.1 Sample code on an event function

The following code provides an example on the configurations on the Code tab of the Function Details page in the Function Compute console:

module.exports.handler = function(event, context, callback) {
    var responseCode = 200;
    console.log("request: " + JSON.stringify(event.toString()));
    // Convert the event to a JSON object.
    event=JSON.parse(event.toString());
    var isBase64Encoded=false;
        // Construct a response body based on the status code that is included in a request. Different response bodies are constructed based on different status codes.
    if (event.queryParameters !== null && event.queryParameters !== undefined) {
        if (event.queryParameters.httpStatus !== undefined && event.queryParameters.httpStatus !== null && event.queryParameters.httpStatus !== "") {
            console.log("Received http status: " + event.queryParameters.httpStatus);
            responseCode = event.queryParameters.httpStatus;
        }
    }
    // If the body of the event parameter is Base64-encoded, perform Base64 decoding on the body content.
    if(event.body!==null&&event.body!==undefined){
            if(event.isBase64Encoded!==null&&event.isBase64Encoded!==undefined&&event.isBase64Encoded){
                    event.body=new Buffer(event.body,'base64').toString();
            }
    }
    // The value of the event parameter is the content that is sent by API Gateway to Function Compute.
    var responseBody = {
        message: "Hello World!",
        input: event
    };
        // Perform Base64 encoding on the body of the response based on your business requirements.
    var base64EncodeStr=new Buffer(JSON.stringify(responseBody)).toString('base64');
        // Return the response in the following format to API Gateway. The value of the isBase64-Encoded parameter varies based on whether the body of the response is Base64-encoded.
    var response = {
                isBase64Encoded:true,
                statusCode: responseCode,
                headers: {
                "x-custom-header" : "header value"
                },
                body: base64EncodeStr
    };
    console.log("response: " + JSON.stringify(response));
    callback(null, response);
};        

3.3.2 Sample code on an API request

In this example, the POST method is used to call an API whose request path is the following string:

/fc/test/invoke/[type]        

The following code describes the request:

POST http://test.alicloudapi.com/fc/test/invoke/test?param1=aaa&param2=bbb
"X-Ca-Signature-Headers":"X-Ca-Timestamp,X-Ca-Version,X-Ca-Key,X-Ca-Stage",
"X-Ca-Signature":"TnoBldxxRHrFferGlzzkGcQsaezK+ZzySloKqCOsv2U=",
"X-Ca-Stage":"RELEASE",
"X-Ca-Timestamp":"1496652763510",
"Content-Type":"application/x-www-form-urlencoded; charset=utf-8",
"X-Ca-Version":"1",
"User-Agent":"Apache-HttpClient\/4.1.2 (java 1.6)",
"Host":"test.alicloudapi.com",
"X-Ca-Key":"testKey",
"Date":"Mon, 05 Jun 2017 08:52:43 GMT","Accept":"application/json",
"headerParam":"testHeader"
{"bodyParam":"testBody"}        

3.3.3 Sample code of an API response

200
Date: Mon, 05 Jun 2017 08:52:43 GMT
Content-Type: application/json; charset=UTF-8
Content-Length: 429
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET,POST,PUT,DELETE,HEAD,OPTIONS , PATCH
Access-Control-Allow-Headers: X-Requested-With, X-Sequence,X-Ca-Key,X-Ca-Secret,X-Ca-Version,X-Ca-Timestamp,X-Ca-Nonce,X-Ca-API-Key,X-Ca-Stage,X-Ca-Client-DeviceId,X-Ca-Client-AppId,X-Ca-Signature,X-Ca-Signature-Headers,X-Forwarded-For,X-Ca-Date,X-Ca-Request-Mode,Authorization,Content-Type,Accept,Accept-Ranges,Cache-Control,Range,Content-MD5
Access-Control-Max-Age: 172800
X-Ca-Request-Id: 16E9D4B5-3A1C-445A-BEF1-4AD8E31434EC
x-custom-header: header value
{"message":"Hello World!","input":{"body":"{\"bodyParam\":\"testBody\"}","headers":{"X-Ca-Api-Gateway":"16E9D4B5-3A1C-445A-BEF1-4AD8E31434EC","headerParam":"testHeader","X-Forwarded-For":"100.81.146.152","Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"},"httpMethod":"POST","isBase64Encoded":false,"path":"/fc/test/invoke/test","pathParameters":{"type":"test"},"queryParameters":{"param1":"aaa","param2":"bbb"}}}
        

4 FAQ

4.1 Why am I unable to use a function that I created in Function Compute as the backend service of an API in API Gateway?

When you create an API that uses Function Compute as the backend service, make sure that the service name and function name that you specify are the same as the names of the service and function that you created in the Function Compute console.

4.2 Is API Gateway able to access Function Compute over an internal network when Function Compute is used as the backend service of an API?

Yes. By default, API Gateway accesses Function Compute over an internal network if event function is selected as the function type and API Gateway resides in the same region as Function Compute.