Community Blog Using API Gateway with Alibaba Cloud's Function Compute

Using API Gateway with Alibaba Cloud's Function Compute

In this tutorial, we will use Alibaba Cloud's Function Compute product to create a function that returns a result to the API Gateway service.

In this tutorial, we will show you how to build an Alibaba Cloud Function Compute function for use by Alibaba Cloud's API Gateway service. We will use Function Compute to create a function that returns a result to the API Gateway service we set up. We will also show you how to monitor your Alibaba Cloud API Gateway service directly from the Function Compute console.

What Is Alibaba Cloud's Function Compute?

Alibaba Cloud's Function Compute is a fully-managed, event-driven compute service for serverless applications. It allows developers to focus on writing and uploading code without having to worry about building and managing complicated infrastructure or operating and maintaining server setups.

Alibaba Cloud's Function Compute service can run many different types of applications, including API gateways, data lake analyses, log stores and backups, web crawlers, and image recognition applications, to name just a few. With Function Compute, developing is convenient and reliable. Function Compute supports many different programming languages including Java, Python, PHP, and NodeJS.

Alibaba Cloud's Function Compute provides real-time auto scaling and dynamic load balancing for managing heavy traffic bursts within millisecond timeframes. Its compute resources ensure that code is flexible and reliable. Furthermore, Function Compute offers a Pay-As-You-Go option which means that you only have to pay for the resources you consume. No fee is incurred if the code doesn't run. Moreover, the code run duration is measured in milliseconds.

Some common business scenarios for Alibaba Cloud's Function Compute include analysis and management of media assets, such as integrating a range of services that run an elastic and highly available backend video system. Another scenario might be to have a serverless backend that triggers Function Compute code which then renders dynamic and static webpages housed in Alibaba Cloud's Object Storage Service. We can also connect Function Compute web services like these to Alibaba Cloud's API Gateway. One further interesting business scenario is implementing Function Compute to manage real time IoT message processing and the monitoring of data streams.

What Is Alibaba Cloud's API Gateway?

Alibaba Cloud's API Gateway service is a fully functional API hosting service that allows you to publish your APIs centrally and offer them to your clients and partners. You can also release your APIs on the Alibaba Cloud API marketplace where other developers may purchase them.

Alibaba Cloud's API Gateway service is a full API lifecycle management service. It provides API definition and publishing, testing, release, and removal. It can generate SDKs and API instructions and has a visualized debugging tool. Alibaba Cloud's API Gateway service increases the efficiency of API management and iterative release. It allows enterprises to flexibly and securely share their technological innovations leaving them free to focus on strengthening and advancing their businesses.

The API Gateway service provides multiple security and efficiency options that include attack defenses, anti-replay, request encryption, identity authentication, permission management, and throttling. Furthermore, Alibaba Cloud's API Gateway service has convenient maintenance, observation, and measurement tools, such as monitoring, alarms, and analysis. It also enables speedy and reliable microservice integration, front and back end separation, and robust system integration at low cost.

Alibaba Cloud's API Gateway service is the ideal service for publishing your APIs and integrates well with other Alibaba Cloud products and services.


You will need an Alibaba Cloud account. If you don't already have one, head over to the Free Trial page to get $300-1200 worth of Alibaba Cloud products to play around with in the Alibaba Cloud Free Trial.

Let's get started.

Create a Function Compute API Gateway Trigger Function

Go to the Alibaba Cloud products console and click through to Function Compute.


In the Function Compute page, click the add button next to Services.


On the slide out, give the service a name and slide open Advanced Settings and scroll down.


In Network config, allow Internet access, then scroll down to Roles.

In Role Config, configure the AliyunApiGatewayFullAccess role.


Check the role details and click Confirm Authorization Policy.


You will see confirmation that your role has been created.

Click OK.


Now click through to the Service you just created.


Let's create a Function. Click the add button next to Functions.


On the template page, select the Empty Function.


Our API Gateway function does not need a Function Compute Trigger so leave the No Trigger setting and click next in Configure Triggers tab.


Give the Function a name and select the runtime environment.

We have chosen Python.


Check the details and configure System Policies for accessing the API Gateway cloud resource.

Click Authorize.


Click Confirm Authorization Policy, then Next.


Then click Next.


Now click Create.


You will find yourself directed to the Function Compute Code Management page.


Now we are ready to code our Function Compute function. However, we will need some info from the API Gateway so let's set that up first.

Create an API in the API Gateway Service

In the Alibaba Cloud products console, click through to API Gateway.


In the API Gateway console, click API Groups.


In your region, make sure you have an API Group.

If not, go ahead and create one by clicking Create Group and giving the API Group a name and an optional description.


Next, go back to APIs in the menu and click Create API.


Give the API a name and select the API Group. We will choose No Certification and leave the selections access restrictions empty for the purposes of the tutorial.

Click Next when you're ready.


Configure the API to have a COMMON Request Type using HTTP and HTTPS Protocols.

The subdomain is the URL variable required by the Function Compute function so make a note of it before configuring a Request Path.

We have used /fcpath

The full path variable we need to input into the Function Compute function is therefore [http://..subdomain../fcpath/]

Function Compute currently does not support Match All Child Paths.

Note the details: The request path must contain the Parameter Path in the request parameter within brackets ([]). For example: /fcpath/[fcparam]

Choose HTTP Method.

For Request Mode we have picked Request Parameter Passthrough.

Scroll down.


Define the path input parameter in the Input Parameter Definition.

You can define a Request Body here too.

We'll leave that for now.

Click Next.


In the Basic Backend Definition, choose Function Compute as the Backend Service Type and select the correct Region.

In the Service and Function name, add your Function Compute Service and Function names.

For Role Arn, click Get Authorization.


API Gateway service will automatically populate the field with the correct role details.

Scroll down.


In the Backend Service Parameter Configuration, you have the details of the path parameter.

Click Next.


Now define the response in the final tab. Scroll down and click Create.


You should see a successful result. Click OK.


Select the API in the list and click Deploy.


Enter the deployment details and click OK.


Click through to the API details.


Click Debug API.


Add the HTTP protocol.

Input and a header to reflect Content-Type : application/json.

Leave the certification as No Certificate.

Scroll down and click Send Request.


You should see a 200 request success code in the output.


Code the Function Compute API Gateway Serverless Function

Go back to Function Compute and enter the following code into the code section.

# -*- coding: utf-8 -*-
import json

def handler(event, context):
    event = json.loads(event)
    content = {
        'path': event['path'],
        'method': event['httpMethod'],
        'headers': event['headers'],
        'queryParameters': event['queryParameters'],
        'pathParameters': event['pathParameters'],
    rep = {
        "isBase64Encoded": "false",
        "statusCode": "200",
        "headers": {
            "x-custom-header": "no"
        "body": content
    return json.dumps(rep)

Click Event to configure the Event parameters.


Add your Custom Event parameters and click OK.


Click Save and Invoke.


You should see a Success message.


Now let's test the API Gateway.

Calling Function Compute from API Gateway

Go back to the API Gateway API and navigate to the debug API page.

The API Gateway is functional.


Monitoring API Gateway with Function Compute

Go back to the Function Compute page and click Monitoring.


In the Monitoring page, you will see a Monitoring Service Overview of Function Compute service usage over time.

Click through to the Service List tab.


You will see all your Services listed. Click through to the API Gateway Service.


You will see a list of all your Functions running as part of the service. Click on a function to see more details.


On the Function Monitoring Overview page, you will see detailed measurements over time for Total Invocations, their Average Duration, Function Errors, and Maximum Memory Usage for the function.

You also have the option to select a specific time range for analysis.


More information on external requests is available in the Request Status Details.


Click through to Create Alarm Rule at the top of the page.

Here you have the option to set an Alarm that will raise a warning whenever your function is under stress, or load, or erroring on a number of different monitoring parameters.


Any Alarm Rules you set are listed under the Alarm Rule tab.



Firstly, we told you about Alibaba Cloud's Function Compute serverless cloud product and how you can use the service to code up multiple types of applications and scenarios.

We then told you about Alibaba Cloud's API Gateway service and how it provides a fully integrated API publishing service for developers. We described how, along with many other Alibaba Cloud services, it integrates with Function Compute to call serverless functions directly from Alibaba Cloud API Gateways.

We explained that the tutorial's goal was to show you how to set up an Alibaba Cloud API Gateway service that calls a backend function in Function Compute.

First, we set up a Function Compute function. Then we set up an Alibaba Cloud API Gateway and configured it to communicate with the Function Compute function. We then wrote some code in Function Compute so that the API Gateway could call the function. Finally, we showed you how to monitor Function Compute functions from within the Function Compute service itself.

In future tutorials we will look at more Function Compute scenarios, Cloud Monitoring, and many other exciting products and services from Alibaba Cloud.

1 0 0
Share on

Alibaba Clouder

2,600 posts | 753 followers

You may also like


RICKY11 September 26, 2020 at 3:34 am

It this the same as plugins?I get an error X-Ca-Error-MessageNo matching JWK EMPTY not foundHowever i have filled out the plugin already.The jwk is not in a X pem format?

Alibaba Clouder

2,600 posts | 753 followers

Related Products

  • Function Compute

    Alibaba Cloud Function Compute is a fully-managed event-driven compute service. It allows you to focus on writing and uploading code without the need to manage infrastructure such as servers.

    Learn More
  • API Gateway

    API Gateway provides you with high-performance and high-availability API hosting services to deploy and release your APIs on Alibaba Cloud products.

    Learn More
  • OSS(Object Storage Service)

    An encrypted and secure cloud storage service which stores, processes and accesses massive amounts of data from anywhere in the world

    Learn More