How to build a Serverless API using AWS Lambda?

Debolina
affinityanswers-tech
5 min readApr 19, 2021

A few months back we were working on a project where we quickly needed to build a public API to give a quick view of our product to our potential customers via web widgets.

The traditional method of building API includes maintaining a server 24/7. We wanted a server-less API so that the pain of maintaining a server could be eliminated. That time we came across AWS Lambda & AWS API Gateway which will serve the purpose of hosting an API without us maintaining it.

What is AWS Lambda Function?

AWS Lambda lets you run code without managing servers. You pay only for the compute time you consume. There is no charge when your code is not running. With this, you can run any code in a lot of languages for backend Service. Just upload your code and Lambda takes care of everything required to run. You can set up your code to automatically trigger from other AWS services.

How does it work?

  1. First, create a lambda function in AWS. We can make it within VPC to secure our privacy.

2. One can write code in Lambda Console. It allows you to run, test and deploy your code there.

3. If any dependant libraries need to be included in the code, then we can use CLI. Write code in EC2 instance, install libraries & then create deployment package & upload it using CLI command. The package should not be more than 50 MB.

4. Or you can just upload a Docker image.

What is AWS API Gateway?

Amazon API Gateway is a fully managed service that allows developers to create, maintain, deploy API endpoint. One can create RESTful API or Websocket API that enables real-time two-way communication applications.

You can secure access to your API with authentication and authorization controls. AWS API Gateway can be integrated with many other AWS services. For our requirement, we used AWS Lambda.

Let’s talk a little bit more about our use case of AWS API in our project. In our application, the front-end requests for the Data from API goes through API Gateway, triggers AWS Lambda which connects to the MySQL server. The response will be sent back to the user.

Application Architecture

I have a sample code down below written in an EC2 instance, just to show how AWS Lambda & AWS API gateway works together to create an endpoint.

Step I: I have created a virtual environment & installed libraries to run the code.

import re
import json
from unidecode import unidecodedef lambda_handler(event, context):
text = "This is a test"
string = "Test"
text = unidecode(text).lower()
string = unidecode(string).lower()
search = re.search(re.escape(string), text, re.I)
if search:
text = "string found"
else:
text = "string not found"

return {
'statusCode': 200,
'headers': {
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'OPTIONS,POST,GET'
},
'body': json.dumps({'code' : 200,'data' : text})
}

Step II: Later I zipped the code & installed libraries in a package and uploaded the package to the lambda function named test using the following command -

aws --region us-west-2 lambda update-function-code --function-name test --zip-file fileb://my-deployment-package.zip

Step III: Now go to AWS Lambda console & test your code. The console lets you see the execution time & RAM usage along with the response like below.

Step IV: If you are happy with the response time deploy it. Otherwise you can change the configurations as per your need.

Step V: Now, next step is to go to the AWS API gateway service and create an API . After the creation you will redirected to a page where you can create an API method (PUT, GET, DELETE, POST etc) & integrate it to the lambda function you want .

Step VI: You can test the method execution (refer to the above gif). Once you are happy with the result deploy it & you get an API endpoint. In addition, you can create an authorizer to control access to your APIs or you can implement rate limitation.

Here you are. You can create an API just in a few minutes. Check the test API endpoint here.

Observation & unanswered questions:

In our project, although the python code was taking milliseconds to execute, after uploading to lambda function it was taking 5 seconds with default 128MB of RAM. To solve this issue we increased the configuration to use 256MB of RAM & the execution time reduced to 3 seconds although it was using only 128MB RAM. But three seconds cannot be considered fast enough for making the API call. As an experiment further we increased the RAM to 1GB and the code took only a few milliseconds to run. The question here is although it was consuming 128 MB of RAM how the execution time kept reducing with the higher configuration of RAM. Can anyone tell me the answer via comments on this blog post?

Last but not the least, you can make 1M free request/month with this service, but you may not want to use it at certain times. Lambda function is not suitable for complex computation or if the code execution time is more than 15 mins or if it takes more than 10 GB of RAM.

Otherwise, we are good to go!!

--

--