All Products
Document Center

Using Function Compute as API Gateway's backend service

Last Updated: Jun 12, 2018

Function Compute is an event-driven service. Function execution can be driven by events. In other words, when a certain event occurs, it triggers a function. Currently, Function Compute supports using API Gateway as an event source. When a request sets Function Compute as the backend service API, API Gateway triggers the corresponding function and Function Compute returns the execution result to API Gateway.

API Gateway interconnects with Function Compute. This allows you to open your function services as APIs and resolves problems including certification, throttling, and data conversion (View API Gateway functions).

Implementation principles

When API Gateway calls Function Compute, the data relevant to the API is converted to Map format for transmission to Function Compute. After the data is processed by Function Compute, the statusCode, other data, body and headers are returned as output as shown in the following figure. Then, API Gateway maps the content returned by Function Compute to statusCode, header, body, and other locations to return it to the client.

Implementation principles

Format of parameters transmitted by API Gateway to Function Compute

When Function Compute is used as a backend service of API Gateway, API Gateway uses a fixed mapping structure to send the request parameter event to Function Compute. Function Compute obtains and processes the expected parameters according to the following structure.

  1. {
  2. "path":"api request path",
  3. "httpMethod":"request method name",
  4. "headers":{all headers,including system headers},
  5. "queryParameters":{query parameters},
  6. "pathParameters":{path parameters},
  7. "body":"string of request payload",
  8. "isBase64Encoded":"true|false, indicate if the body is Base64-encode"
  9. }


  • If "isBase64Encoded" is set to "true", it indicates that the API Gateway uses Base64 to encode the body content transmitted to Function Compute. Before processing the body content, Function Compute must perform Base64 decryption.

  • If "isBase64Encoded" is set to "false", it indicates that the API Gateway does not use Base64 to encode the body content.

Format of parameters returned by Function Compute

Function Compute must output the content to return to API Gateway using the following JSON format, to facilitate parsing by API Gateway.

  1. {
  2. "isBase64Encoded":true|false,
  3. "statusCode":httpStatusCode,
  4. "headers":{response headers},
  5. "body":"..."
  6. }


  • When the body content is encoded in a binary format, you must use Base64 to encode the body content in Function Compute and set "isBase64Encoded" to "true". If the body content does not need to be encoded in Base64 format, set "isBase64Encoded" to "false". When "isBase64Encoded" is "true", API Gateway performs Base64 decryption on the body content before returning it to the client.

  • In a Node.js environment, Function Compute sets callback based on the specific situation.

    • To return a successful message: callback{null,{“statusCode”:200,”body”:”…”}}.

    • To return an exception: callback{new Error(‘internal server error’),null}.

    • To return a client error: callback{null,{“statusCode”:400,”body”:”param error”}}.

  • If the format of the result returned by Function Compute does not conform to the format requirements, API Gateway returns 503 Service Unavailable to the client.

Create an API with Function Compute as the backend service

Follow these steps to create an API with Function Compute as a backend service.

  1. Create a function in the Function Compute console

  2. Create and define a Function Compute backend service API

  3. Debug the API

  4. Publish the API to the production environment

Create a function in the Function Compute console

  1. Create a service. Log on to the Function Compute console, select the Region of the service and function to create and click Create Service. In the dialog box,complete the service creation process.

    Note: After creating the service, you cannot change its region, therefore, make sure you select the correct region.

    Create a service

  2. Create a function in the created service. On the page of this newly created service, click Create Function to enter the function creation process:

    1. Select a function template.

      The Function Compute console provides an API Gateway backend implementation template for the Node.js 6 environment: api-gateway-nodejs6.

      If the api-gateway-nodejs6 template does not suit your business needs, select Empty Function. After selecting the Blank Function template, you must provide your own code in Basic Management Configuration. To finish the upload, prepare your code package in advance.

      Select sample

    2. Configure the trigger. Select No Trigger and click Next.

    3. Configure function settings: Enter basic information, configure the code, set environment variables, and configure the environments. Then, click Next.

    4. Ignore Service Role Management step and click Next.

      As we have already configured the corresponding role Arn permissions in the RAM console, you do not have to configure service role here. When creating an API in the API Gateway console, you click Get Authorization to automatically obtain the required role Arn.

    5. Check that all the information is correct and then click Create.

      After creating the function, you can review its basic information in the Function List.

Create and define a Function Compute backend service API

You must create an API in the API Gateway console and define its backend service as Function Compute.

  1. Log on to the API Gateway console.

  2. Create a group.

    Click API Groups from the left-side navigation pane, select a region for the group, and click Create Group. (Skip this step if you have already created a group.)

    Note: If Function Compute and the API are in different regions, your Function Compute service is accessed over the Internet.

    If you have high data security and network latency requirements, create the API in the same region as the function.

    Create a group

    After creating the API group, you can use Environment Management to set environment variables for this group. APIs can be used in three environments: Test, Pre, and Release. To avoid backend address changes because of environment conversations, you can add environment variable parameters to implement automatic request routing. For the environment variable configuration method, see Environment management.

  3. Create and define an API.

    1. After creating the group, click the View APIs button from the Operation column of this group to go to its API List page.

    2. Click Create API to enter the API creation and definition process.

    3. Enter the basic information of the API and click Next.


    4. Define API requests and click Next.

      Note: If the Request Mode is set to Request Parameter Passthrough, the parameter body content sent to API Gateway is not processed, and is forwarded directly to Function Compute.

      Create an API

    5. Define the API backend service and click Next.

      Note: On this page, you must:

      • Set the Backend Service Type to Function Compute.

      • Enter the name of the service you created in the Function Compute console as the Service Name.

      • Enter the name of the function you created in the Function Compute console as the Function Name.

      • Click Get Authorization to automatically obtain the role Arn.

        If this is the first time you have obtained role authorization for Function Compute as the API Gateway backend service, after you click Get Authorization, the RAM console’s authorization page is displayed. You must click the policy to grant permission on the RAM console, and then return to the API creation page and click Get Authorization again. The role Arn is then automatically displayed in the selection box.

      Define backend service

    6. Define response and then click Create.

      Note: a returned result sample is required and the format must follow the Format of parameters returned by Function Compute.

      Define response

      For more information, see Create an API.

Debug the API

After you create and define an API, the interface automatically displays the API List page. You can test whether the created API is usable and the request chain is correct.

  1. On the API List page, click the API name or the Manage button to go to the API Definition page.

  2. Click Debug API on the left-side navigation pane.

  3. Input the request parameters and click Send Request.

    The returned results are displayed on the right-side of the page.

    If it returns a successful result, it indicates that the API can be used.

    If a 4XX or 5XX error code is returned, it indicates that the request has encountered an error. For more information, see How to obtain the error message and Error code table.

  4. Publish the API to the Pre environment for testing before it goes online.

    After testing proves the API is usable, you can return to the API Definition page and publish the API to the Pre environment. Then, use the subdomain name to simulate real user requests to test calling.

    Note: If an environment variable is set in the API definition, enter the parameter X-Ca-Stage: RELEASE in the header to call the pre-release environment API.

Publish the API to the production environment

After you debug the API to prove it can be used, you can publish it.

  1. On the API List page, click the API name or the Manage button to go to the API Definition page.

  2. Click the Publish button in the upper-right corner of the page to bring up the Publish API dialog box.

  3. Select Release, enter remarks, and click Publish.

    After the API is published to the production environment, your users can call it.

For more information about publishing, see the Publish an API document.


The three samples namely a function code sample, API request sample, and API Gateway return sample are described as follows.

Function code sample

This is a sample of code configured in Function Compute.

  1. module.exports.handler = function(event, context, callback) {
  2. var responseCode = 200;
  3. console.log("request: " + JSON.stringify(event.toString()));
  4. //Converts the event to a JSON object.
  5. event=JSON.parse(event.toString());
  6. var isBase64Encoded=false;
  7. //Returns the result for the statusCode you enter; used to test scenarios with different statusCode values
  8. if (event.queryParameters !== null && event.queryParameters !== undefined) {
  9. if (event.queryParameters.httpStatus !== undefined && event.queryParameters.httpStatus !== null && event.queryParameters.httpStatus !== "") {
  10. console.log("Received http status: " + event.queryParameters.httpStatus);
  11. responseCode = event.queryParameters.httpStatus;
  12. }
  13. }
  14. //If the body is Base64 encoded, Function Compute must decode the body content
  15. if(event.body!==null&&event.body!==undefined){
  16. if(event.isBase64Encoded!==null&&event.isBase64Encoded!==undefined&&event.isBase64Encoded){
  17. event.body=new Buffer(event.body,'base64').toString();
  18. }
  19. }
  20. //input is the content that API Gateway inputs to Function Compute
  21. var responseBody = {
  22. message: "Hello World!",
  23. input: event
  24. };
  25. //Base64 encodes the body content, can be set according to your actual needs
  26. var base64EncodeStr=new Buffer(JSON.stringify(responseBody)).toString('base64');
  27. //Format of the result that Function Compute returns to API Gateway; must conform to the following requirements: Set isBase64Encoded according to whether the body must be Base64 encoded
  28. var response = {
  29. isBase64Encoded:true,
  30. statusCode: responseCode,
  31. headers: {
  32. "x-custom-header" : "header value"
  33. },
  34. body: base64EncodeStr
  35. };
  36. console.log("response: " + JSON.stringify(response));
  37. callback(null, response);
  38. };

Sample request

A POST format request path for the following API:

  1. /fc/test/invoke/[type]
  1. POST
  2. "X-Ca-Signature-Headers":"X-Ca-Timestamp,X-Ca-Version,X-Ca-Key,X-Ca-Stage",
  3. "X-Ca-Signature":"TnoBldxxRHrFferGlzzkGcQsaezK+ZzySloKqCOsv2U=",
  4. "X-Ca-Stage":"RELEASE",
  5. "X-Ca-Timestamp":"1496652763510",
  6. "Content-Type":"application/x-www-form-urlencoded; charset=utf-8",
  7. "X-Ca-Version":"1",
  8. "User-Agent":"Apache-HttpClient\/4.1.2 (java 1.6)",
  9. "Host":"",
  10. "X-Ca-Key":"testKey",
  11. "Date":"Mon, 05 Jun 2017 08:52:43 GMT","Accept":"application/json",
  12. "headerParam":"testHeader"
  13. {"bodyParam":"testBody"}

API Gateway return sample

  1. 200
  2. Date: Mon, 05 Jun 2017 08:52:43 GMT
  3. Content-Type: application/json; charset=UTF-8
  4. Content-Length: 429
  5. Access-Control-Allow-Origin: *
  6. Access-Control-Allow-Methods: GET,POST,PUT,DELETE,HEAD,OPTIONS , PATCH
  7. 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
  8. Access-Control-Max-Age: 172800
  9. X-Ca-Request-Id: 16E9D4B5-3A1C-445A-BEF1-4AD8E31434EC
  10. x-custom-header: header value
  11. {"message":"Hello World!","input":{"body":"{\"bodyParam\":\"testBody\"}","headers":{"X-Ca-Api-Gateway":"16E9D4B5-3A1C-445A-BEF1-4AD8E31434EC","headerParam":"testHeader","X-Forwarded-For":"","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"}}}


Why can’t I input an existing function?

You must make sure that the service and function names you enter are consistent with the names used to create the service and function on the Function Compute console.

Can I set multiple functions as an API’s backend service?

No. Currently, one API can be mapped to one particular function only.