All Products
Search
Document Center

API Gateway:Function Compute

Last Updated:Nov 20, 2024

Function Compute is an event-driven service. 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. This topic uses Function Compute 3.0 as an example to describe how to integrate API Gateway with Function Compute services.

Prerequisites

An API Gateway instance is created. For more information , see Choose an instance type.

Overview

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

Integrate an HTTP function with API Gateway

Create a web function

Before you integrate Function Compute with API Gateway, you must create a web function in the Function Compute 3.0 console. For more information, see Create a web function.

Create a backend service

You must create a backend service in API Gateway and configure a URL for the backend service to point to your Function Compute service.

  1. Log on to the API Gateway console. In the left-side navigation pane, choose Manage APIs > Backend Services. In the top navigation bar, select a region. Then, click Create Backend Service.

    image

  2. In the Create Backend Service dialog box, configure the parameters as shown in the following figure and click Confirm.

    image

  3. On the Backend Services page, click the created backend service. On the Backend Service Definition page, click the Production tab. In the Basic Information section, click Create in the upper-right corner.

    image

  4. On the Basic Information page, configure the Trigger Path parameter and click Publish.

    image

Create an API

Create an API in the API Gateway console. For more information, see Step 3: Create an API.

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

Note

If the API group is created in a different region than the Function Compute function, API Gateway accesses the function over the Internet, which incurs traffic fees. If you require high data security and low network latency, select the region where you created the function in Function Compute to create the API group.

  • Create and define an API. In the Define Backend Service step of the Create API wizard, configure the following parameters:

image

Configuration Mode: Select Use Existing Backend Service.

Backend Service Type: Select Function Compute.

Version: Select Function Compute V3.0.

Function Type: Select HTTP Function.

Backend Service: Select FC-backend.

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.

Use the Function Compute function of another account

API Gateway allows you to use the Function Compute function of another account to integrate with your API. The following section describes how to allow API Gateway within Account A to access a function of Account B.

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

    Step 1: Log on to the Resource Access Management (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 Grant 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 Alibaba Cloud Resource Name (ARN) of the RAM role for Account A. For more information, see the "Terms" section of the RAM role overview topic.

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

Integrate an event function with API Gateway

Create an event function

For more information about how to create an event function in the Function Compute 3.0 console, see Create an event function.

Create a backend service

You must create a backend service in API Gateway and configure a URL for the backend service to point to your Function Compute service.

  1. Log on to the API Gateway console. In the left-side navigation pane, choose Manage APIs > Backend Services. In the top navigation bar, select a region. Then, click Create Backend Service in the upper-right corner and configure the following parameters:

    image

  2. On the Backend Services page, click the created backend service. On the Backend Service Definition page, click the Production tab. In the Basic Information section, click Create in the upper-right corner.

    image

  3. Select the created event function and click Publish.

    image

Create an API

Create an API in the API Gateway console. For more information, see Step 3: Create an API.

  • 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

Configuration Mode: Select Use Existing Backend Service.

Backend Service Type: Select Function Compute.

Version: Select Function Compute V3.0.

Function Type: Select Event Function.

Backend Service: Select the created backend service.

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 in an invalid format, API Gateway returns the following error message to the client: 503 Service Unavailable.

Examples of event function invocations

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

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);
};        

Event function 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 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"}        

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"}}}
        

FAQ

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.

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.