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

Based on the integration with Function Compute, API Gateway allows you to provide API operations in a secure manner and supports features such as authentication, throttling, and data conversion. For more information, see Features.

How it works

After API Gateway receives a request for an API operation with 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, header, and body, as shown in the following figure. API Gateway maps the information in the response that is returned by Function Compute to the status code, header, 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 operation with 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. Function Compute obtains required parameters from the key-values pairs that are sent from API Gateway, as shown in the following code snippet:

{
	"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 content that API Gateway sent to Function Compute is Base64-encoded. To trigger the corresponding function, Function Compute needs to perform Base64 decoding on the body content first.
  • If the value of "isBase64Encoded" is "false", API Gateway did not perform Base64 encoding on the body content that was sent to Function Compute.

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

Function Compute sends the execution result of the corresponding function to API Gateway in the JSON format, as shown in the following code snippet. API Gateway will parse the response that Function Compute returns.

{
	"isBase64Encoded":true|false,
	"statusCode":httpStatusCode,
	"headers":{response headers},
	"body":"..."
}
  • If the body content of the response is binary data, Function Compute needs to perform Base64 encoding on the body content. The value of "isBase64Encoded" is "true" in the response that is sent to API Gateway. If Function Compute does not need to perform Base64 encoding on the body content of the response, the value of "isBase64Encoded" is "false". If the value of "isBase64Encoded" is "true" in the response that is sent from Function Compute, API Gateway performs Base64 decoding on the body content of the response before API Gateway sends the mapped API response to the client.
  • In the Node.js environment, Function Compute constructs a callback parameter based on different execution results:
    • If the result 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 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 to be sent to API Gateway is an error response 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 an error message "503 Service Unavailable" to the client.

Procedure

To create an API operation with Function Compute as the backend service in API Gateway, perform the following steps:

  1. Create a function in the Function Compute console.
  2. Create an API operation with Function Compute as the backend service in the API Gateway console.
  3. Debug the API operation.
  4. Publish the API operation to the production environment.

Create a function in the Function Compute console

  1. Create a service. Log on to the Function Compute console. Select a region where you want to create the service and function in the top navigation bar. Click Service/Function in the left-side navigation pane. On the Service/Function page, click the drop-down arrow next to Create Function and click Create Service. On the page that appears, set relevant parameters. Note that after a service is created, you cannot change the region where the service resides. Proceed with caution when you select a region.

  2. Create a function in the service you created. After you create the service, the service appears on the Service/Function page. Select the service and click Create Function. The Create Function wizard appears.
    1. In the Create Function step, click Template Function in the Function Type section and select a function template.

      The Function Compute console provides the api-gateway-nodejs6 template for you to create a function as the backend service of an API operation in Node.js 6.

      If the api-gateway-nodejs6 template is not applicable to your business scenario, click Event Function in the Function Type section. If you create an event function, you must upload your own code in the runtime environment of the function. We recommend that you prepare your code in advance.
    2. For information about how to write code for a function, see the "Write code for a function" section in API Gateway triggers Function Compute.

Create and configure an API operation with Function Compute as the backend service

After you create the function in the Function Compute console, you must create an API operation with Function Compute as the backend service in the API Gateway console.

  1. Log on to the API Gateway console.
  2. In the left-side navigation pane, choose Publish APIs > API Groups. Select a region in the top navigation bar and click Create Group. If you have created an API group, skip this step.
    Note If the region where you created the API group is not the same region where you created the service in Function Compute, API Gateway will access the service in Function Compute by using the Internet. If you need high data security and low network latency, select the region where you created the service in Function Compute when you create the API group in API Gateway.
    After the API Group is created, you can find it on the Group List page and click View Stages in the Operation column. On the Stage Management page, you can configure environment variables for the API group. API Gateway supports three environments: Test, Pre, and Release. To prevent environment switch from changing the backend service address of an API operation, you can configure an environment variable to implement automatic routing of API requests. For more information about how to configure environment variables, see Configure different environments for an API operation.
  3. Create and configure an API operation.
    1. On the Group List page, find the API group you created and click View APIs in the Operation column. The API List page of the API group appears.
    2. Click Create API. The Create API wizard appears.
    3. In the Basic Information step, configure basic information for the API operation and click Next.
    4. In the Define API Request step, configure request information for the API operation and click Next.
      Note If you set Request Mode to Request Parameter Passthrough, API Gateway does not handle request parameters in each API request and directly forwards the request to Function Compute.
    5. In the Define API Backend Service step, configure a backend service for the API operation and click Next.
      Note In this step, set Backend Service Type to FunctionCompute. In the Service Name field, enter the name of the service that you created in the Function Compute console. In the Function Name field, enter the name of the function that you created in the Function Compute console. Click Get Authorization next to the Role Arn field. If this is the first time you create an API operation with Function Compute as the backend service, the Auto Authorize message appears after you click Get Authorization. Click Authorize in the message. The Cloud Resource Access Authorization page appears. Click Confirm Authorization Policy. Go back to the Define API Backend Service step in the API Gateway console. Click Get Authorization again. A value is automatically entered in the Role Arn field.
    6. In the Define Response step, configure response information for the API operation and click Create.
      Note You must enter a sample response in the Sample of Returned Results field. For information about the response format, see Output format of the response that Function Compute sends to API Gateway.
      For more information about how to create an API operation, see Create an API operation.

Debug the API operation

After the configurations of the API operation are completed, you are navigated to the **API List** page. To debug the API operation, perform the following steps:

1. Find the API operation you created and click its name or click Manage in the Operation column. The API Definition page appears.

2. In the left-side navigation pane, click Debug API.

3. On the page that appears, specify request parameters in the Request Parameters section and click Send Request.

A result appears on the right of the page.

If the result is a success response, the API operation can be called.

If the result includes an error code that starts with the digit 4 or 5, an error occurred in the process of calling the API operation. For more information, see How to obtain the error message and Error code table.

4. Publish the API operation to the staging environment for testing.

After the debugging proves the API operation available, go back to the API Definition page. Click Deploy in the upper-right corner. In the Deploy API dialog box, select Pre to publish the API operation to the staging environment. Then, simulate a user call. Call the API operation by using the default second-level domain name that is automatically bound to the API group to which the API operation belongs.

Note: If you have configured an environment variable for the API operation, you must add the key-value pair X-Ca-Stage: PRE in the request header when you call the API operation in the staging environment.

Publish the API operation to the production environment

After the API operation is debugged and proved to be ready for use, you can publish the API operation to the production environment.

1. On the API List page, find the API operation you created and click its name or click Manage in the Operation column. The API Definition page appears.

2. Click Deploy in the upper-right corner. The Deploy API dialog box appears.

3. Set the Select The Stage To Release To parameter to Release, enter your remarks, and then click Deploy.

After you publish the API operation to the production environment, other users can call the API operation.

For more information about how to publish an API operation, see Create an API operation with HTTP as the backend service.

Sample code

The following code snippets are samples of a function, an API request, and an API response, respectively.

Sample code of a function

The following code snippet is the sample code for configuring a function in Function Compute:

module.exports.handler = function(event, context, callback) {
    var responseCode = 200;
    console.log("request: " + JSON.stringify(event.toString()));
    // Convert an event to 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 content 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 API Gateway sends to Function Compute.
    var responseBody = {
        message: "Hello World!",
        input: event
    };
	
	// Perform Base64 encoding on the body content of the response if needed.
    var base64EncodeStr=new Buffer(JSON.stringify(responseBody)).toString('base64');
	
	// Return the response in the following format to API Gateway. The value of the isBase64Encoded parameter depends on whether the body content 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);
};	

Sample code of an API request

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

/fc/test/invoke/[type]	
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"}	

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

FAQ

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

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

Can I use multiple functions as the backend service of an API operation?

No, you cannot use multiple functions as the backend service of an API operation. For each API operation with Function Compute as the backend service, you can configure only one function as the backend service of the API operation.