Using API Gateway with Alibaba Cloud’s Function Compute

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.

Prerequisites

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.

Image for post
Image for post

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

Image for post
Image for post

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

Image for post
Image for post

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

In Role Config, configure the AliyunApiGatewayFullAccess role.

Image for post
Image for post

Check the role details and click Confirm Authorization Policy.

Image for post
Image for post

You will see confirmation that your role has been created.

Click OK.

Image for post
Image for post

Now click through to the Service you just created.

Image for post
Image for post

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

Image for post
Image for post

On the template page, select the Empty Function.

Image for post
Image for post

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

Image for post
Image for post

Give the Function a name and select the runtime environment.

We have chosen Python.

Image for post
Image for post

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

Click Authorize.

Image for post
Image for post

Click Confirm Authorization Policy, then Next.

Image for post
Image for post

Then click Next.

Image for post
Image for post

Now click Create.

Image for post
Image for post

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

Image for post
Image for post

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.

Image for post
Image for post

In the API Gateway console, click API Groups.

Image for post
Image for post

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.

Image for post
Image for post

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

Image for post
Image for post

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.

Image for post
Image for post

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

The full path variable we need to input into the Function Compute function is therefore []

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:

Choose HTTP Method.

For Request Mode we have picked Request Parameter Passthrough.

Scroll down.

Image for post
Image for post

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.

Image for post
Image for post

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.

Image for post
Image for post

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

Scroll down.

Image for post
Image for post

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

Click Next.

Image for post
Image for post

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

Image for post
Image for post

You should see a successful result. Click OK.

Image for post
Image for post

Select the API in the list and click Deploy.

Image for post
Image for post

Enter the deployment details and click OK.

Image for post
Image for post

Click through to the API details.

Image for post
Image for post

Click Debug API.

Image for post
Image for post

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.

Image for post
Image for post

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

Image for post
Image for post

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.

Image for post
Image for post

Add your Custom Event parameters and click OK.

Image for post
Image for post

Click Save and Invoke.

Image for post
Image for post

You should see a Success message.

Image for post
Image for post

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.

Image for post
Image for post

Monitoring API Gateway with Function Compute

Go back to the Function Compute page and click Monitoring.

Image for post
Image for post

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.

Image for post
Image for post

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

Image for post
Image for post

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

Image for post
Image for post

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.

Image for post
Image for post

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

Image for post
Image for post

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.

Image for post
Image for post

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

Image for post
Image for post

Summary

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.

Reference:

https://www.alibabacloud.com/blog/using-api-gateway-with-alibaba-clouds-function-compute_594695?spm=a2c41.12784890.0.0

Written by

Follow me to keep abreast with the latest technology news, industry insights, and developer trends.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store