All Products
Search
Document Center

API Gateway:Function Compute

Last Updated:Jan 09, 2024

Function Compute is an event-driven service. For more information, see Function type selection. If you integrate Function Compute with API Gateway, you can use API Gateway to open functions to the public as APIs in a secure manner. This allows API Gateway to authenticate users, throttle calls, and convert data for you.

1. Overview

API Gateway supports two types of functions: HTTP functions and event functions.

2. Integrate an HTTP function with API Gateway

2.1 Create an HTTP function

Before you configure parameters in the API Gateway console, you must create a function that is configured with an HTTP trigger in the Function Compute console. For more information, see Configure an HTTP trigger that invokes a function with HTTP requests.

2.2 Create an API

Note

For more information about how to create an API in the API Gateway console, see Create an API with Function Compute as the backend service in Getting Started. This topic describes the operations that require your considerations.

  • Create an API group. We recommend that you create the API group in the same region as your Function Compute function.

Note

If the region where you create the API group is not the same region where you created the service in Function Compute, API Gateway accesses the service in Function Compute over the Internet, which incurs traffic fees. If you require high data security and low network latency, make sure that the region of the API is the same as the region of the function.

  • Create and define an API. In the Define Backend Service step of the Create API wizard, take note of specific parameters. The following figure shows all parameters in the step.

Backend Service Type: Select Function Compute.

Call Method: Select HTTP Trigger.

Trigger Path: Use the trigger path that is displayed on the Triggers tab of the Function Details page of the function in the Function Compute console. If you call the function in the same region, you can replace the domain name in the trigger path with an internal endpoint. If you want to use an internal endpoint, perform the following operations: Go to the Function Compute console, click Services & Functions in the left-side navigation pane, click the desired service, click the desired HTTP function in the functions list, click the Trigger Management (URL) tab, and find the internal endpoint on the tab.

Backend Request Path: Specify a custom path. If you do not want to specify a custom path, enter a forward slash (/).

HTTP Method: Select a method that is supported by Function Compute. If you want to specify multiple methods, select ANY.

Role ARN: Specify the Alibaba Cloud Resource Name (ARN) of the Resource Access Management (RAM) role that you want to use to authorize API Gateway to access Function Compute. By default, you can follow instructions in the API Gateway console to configure the role ARN to allow access from API Gateway to Function Compute within the same Alibaba Cloud account.

2.3 Use Function Compute deployed within another account

API Gateway allows you to use Function Compute that is deployed within your Alibaba Cloud account or another Alibaba Cloud account as a backend service. The following section describes how to allow API Gateway within an Alibaba Cloud account to use Function Compute that is deployed within another Alibaba Cloud account. In this example, Function Compute within Account B is used by API Gateway within Account A.

  1. Use Account B to perform the following steps to authorize API Gateway within Account A to access Function Compute within Account B:

    Step 1: Log on to the RAM console by using Account B and create a RAM role. For more information, see Create a RAM role for a trusted Alibaba Cloud account.

    Step 2: Attach the AliyunFCInvocationAccess policy to the RAM role created in Step 1. This policy allows the RAM role to access Function Compute. For more information, see the "Method 1: Grant permissions to a RAM role by clicking Add Permissions on the Roles page" section of the Grant permissions to a RAM role topic.

    Step 3: Add the ID 123456789012**** of Account A to the trust policy of the RAM role to modify the trust policy. For more information, see the "Example 1: Change the trusted entity of a RAM role to an Alibaba Cloud account" section of the Edit the trust policy of a RAM role topic. The following sample code provides an example of the modified trust policy:

{
  "Statement": [
    {
      "Action": "sts:AssumeRole",
      "Effect": "Allow",
      "Principal": {
        "Service": [
          "123456789012****@apigateway.aliyuncs.com"
        ]
      }
    }
  ],
  "Version": "1"
}

Step 4: Provide the ARN of the RAM role for Account A. For more information, see the "Terms" section of the RAM role overview topic.

  1. Use Account A in the API Gateway console to specify the information that is required to allow the access from API Gateway within Account A to Function Compute within Account B. The content of the trigger path is the endpoint of Function Compute within Account B. The role ARN is the role ARN that is provided in Step 4.

Important

When an HTTP function is used as the backend service of an API, the Authorization value in a request sent from a client is overwritten by the Authorization value of the HTTP function. We recommend that you use another parameter in your requests.

3. Integrate an event function with API Gateway

3.1 Create an event function

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

3.2 Create an API

Note

For more information about how to create an API in the API Gateway console, see Create an API with Function Compute as the backend service in Getting Started. This topic describes the operations that require your considerations.

  • Create an API group. We recommend that you create the API group in the same region as your Function Compute function.

Note

If the region where you create the API group is not the same region where you created the service in Function Compute, API Gateway accesses the service in Function Compute over the Internet, which incurs traffic fees. If you require high data security and low network latency, make sure that the region of the API is the same as the region of the function.

  • Create an API. In the Define Backend Service step of the Create API wizard, take note of specific parameters. The following figure shows all parameters in the step.

image

Function Type: Select Event Function.

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

3.3 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 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 data such as the statusCode, headers, and body parameters. The following figure shows the output format of the response. API Gateway maps the data in the response to specific parameters of an API response, such as the statusCode, headers, and body parameters, and returns the API response to the client.

Input format of the 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 and passes the request parameters to Function Compute as the value of the event parameter. Then, Function Compute obtains the required parameters from the request parameters in the Map format and handles the request. The following sample code provides an example of the required parameters:

{
        "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. In this case, Function Compute must decode the request body in Base64 before handling the request.

  • 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 parameters that Function Compute returns to API Gateway

The response that Function Compute returns to API Gateway is in the JSON format. This allows API Gateway to parse the response. The following sample code provides an example of the response in the JSON format:

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

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

    • If Function Compute returns a successful response, the value of the callback parameter is in the following format: callback(null,{"statusCode":200,"body":"..."}).

    • If Function Compute returns an exception, the value of the callback parameter is in the following format: callback(new Error('internal server error'),null).

    • If Function Compute returns a client error, 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 following error message to the client: 503 Service Unavailable.

3.4 Examples on the invocation of an event function

The following section provides sample code of an event function, an API request, and an API response.

3.4.1 Sample code of an event function

The following section provides the sample code 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 value of the event parameter into a JSON object.
    event=JSON.parse(event.toString());
    var isBase64Encoded=false;
        // Construct a response body based on the status code that is specified 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, decode the body in Base64 in Function Compute.
    if(event.body!==null&&event.body!==undefined){
            if(event.isBase64Encoded!==null&&event.isBase64Encoded!==undefined&&event.isBase64Encoded){
                    event.body=new Buffer(event.body,'base64').toString();
            }
    }
    // Set the input parameter to the content that is sent from API Gateway to Function Compute.
    var responseBody = {
        message: "Hello World!",
        input: event
    };
        // Encode the response body in Base64 based on your business requirements.
    var base64EncodeStr=new Buffer(JSON.stringify(responseBody)).toString('base64');
        // Specify the response that Function Compute returns to API Gateway in the following format: The value of the isBase64Encoded parameter varies based on whether the response body 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.4.2 Sample code of an API request

The following sample code provides an example of the path of an API request. In this example, the POST method is used to call the API.

/fc/test/invoke/[type]        

The following sample code provides an example of the API 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.4.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 Can API Gateway access Function Compute over a private network when Function Compute is used as the backend service of an API?

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