DEV Community

Deepak Poudel
Deepak Poudel

Posted on

Serverless API Deployment with AWS Lambda and API Gateway

Serverless API Deployment with AWS Lambda and API Gateway
Introduction:
Serverless API deployment with AWS Lambda and API Gateway is a cloud computing model in which an application runs on a serverless architecture without the need to manage servers, operating systems, or infrastructure. With AWS Lambda, developers can write code in response to various triggers, such as an HTTP request, and the code will execute without requiring a server to be running at all times. AWS API Gateway is a fully managed service that enables developers to create, publish, and manage APIs at scale.

In a serverless API deployment, AWS Lambda functions act as the backend code for an API Gateway API. The API Gateway is responsible for handling requests from clients and forwarding them to the appropriate AWS Lambda function. The Lambda function performs the necessary operations and returns a response to the API Gateway, which sends the response back to the client.

The benefits of serverless API deployment with AWS Lambda and API Gateway include:
● Reduced operational overhead: With a serverless deployment model, there is no need to manage servers, operating systems, or infrastructure, which reduces operational overhead.
● Scalability: Serverless architectures can scale automatically in response to changes in demand, allowing APIs to handle many requests without needing manual scaling.
● Cost-effectiveness: Serverless APIs can be cost-effective because they are charged based on the number of requests and the execution time rather than the amount of server time used.
● Ease of development: AWS Lambda and API Gateway provide a simple and intuitive interface for developing, testing, and deploying serverless APIs, which can speed up the development process.
● Security: AWS Lambda and API Gateway provide robust security features, such as identity and access management, encryption, and monitoring, to help protect serverless APIs from security threats.
Pricing:
AWS Lambda:
AWS Lambda pricing is based on the number of requests and the duration of each function execution. AWS Lambda offers a generous free tier of 1 million requests and 400,000 GB-seconds of monthly compute time. After that, pricing is based on the number of requests, the duration of each execution, and the amount of memory the function uses.

API Gateway:
API Gateway pricing is based on the number of API calls and data transfers out. There is a free tier of 1 million API calls per month and up to 12 months of free data transfer out. After that, pricing is based on the number of API calls and the amount of data transferred out.

Steps:

  1. Sign in to the AWS Management Console and navigate the lambda service.

Image description
1.Choose to Create a function
Image description
1 Create a function
● Choose an Author from scratch
● choose runtime: AWS Lambda supports various programming languages, including Java, Python, Node.js, Go, and others. You can choose the language that best fits your needs and expertise.
● Choose Architecture: x86_64
Expand Change default execution role and check to Create a new role with basic Lambda permission

Image description

Image description
● You will see a page similar to the page below

Image description

  1. Modify the default lambda_function ● We will modify the lambda function to call API using the requests library ● I am taking a dummy API from https://dummyjson.com/

Image description
● The code looks like this

Image description
Code :

import json
import requests
def lambda_handler(event, context):
base_url = 'https://dummyjson.com/'
product_id = '1'
resp = requests.get(url=base_url+'products/'+product_id)
if resp.status_code != 200:
raise Exception('Failed to retrieve product: '+resp.text)
return {
'statusCode': resp.status_code,
'body': resp.json()
}
Q. what this code does?
1.Imports the necessary modules (JSON and requests).
2.Defines a base URL and a product ID that will be used to construct the API URL.
3.Sends a GET request to the API using the requests library, passing in the full API URL.
4.Checks the response status code to make sure that the request was successful (status code 200).
5.If the response status code is not 200, raise an exception with an error message that includes the response text.
6.If the response status code is 200, return a dictionary containing the response status code and the parsed JSON response body.
●Test the function.

Image description

  1. Create a test event

Image description
● You will get an error as shown:

Image description
Q. why do we get this error, and how to solve it?
➢ This is because there are no library-named requests. Now here comes the use of lambda layers.

Lambda layers:
AWS Lambda Layers are a way to manage common code and libraries in AWS Lambda functions. A layer is essentially a ZIP archive that contains libraries, custom runtimes, or other dependencies that multiple functions in your AWS account can use. Instead of bundling all the code and dependencies within each Lambda function, you can create a layer that includes common libraries or code and then associates that layer with one or more functions. This can help reduce the size of your function code and simplify updates to shared code or libraries.

  1. Fix the error ● Goto your local system and create a directory ● Install the required libraries in our case requests library ● Zip the folder containing libraries

Image description

● Goto lambda dashboard, Select layers, and click create layer

Image description

Image description
● Give name, description and upload the file you zipped in the above step
● Choose compactable architecture and runtimes and create

  1. Add layer Image description

Image description

1.Test the lambda function

Image description

Image description
Now the code is successfully executed.
1.Create an API Gateway
● Goto AWS Management Console and navigate the API Gateway service

Image description
Choose REST API

Image description
● Create API

Image description
●Goto actions and Create Method

Image description
●Select GET , Setup and Save
-We are integrating with Lambda function so choose integration type to lambda function
-Choose Lamba region
-Choose the Lamba created in above
-Save

Image description

Image description

● Add Permission to Lambda Function

Image description
Test

Image description

Image description

Image description

You can see the response of our API is according to our desire

●Enable CORS:
Enabling CORS (Cross-Origin Resource Sharing) in API Gateway allows web applications from different domains to access resources served by your API.

Without CORS, web applications can only make requests to endpoints on the same domain where the application is hosted. If you enable CORS, you allow requests to be made from other domains, which can be useful for building web applications that use APIs hosted on a different domain.

Image description

Image description

Image description

● Deploy API
-Give stage name and description(optional)

Image description

Image description
We have successfully deployed our API and got the invoke URL
● Execute Lambda function when API is triggered
-Goto Lambda page and click Add trigger

Image description
-Set trigger configuration as shown below

Image description

● Paste the invocation URL in the browser you will see the desired output in JSON format

Image description
Conclusion:
In conclusion, AWS Lambda and API Gateway are powerful services that can be used to build and deploy scalable, cost-effective APIs quickly and easily. With Lambda, you can run your code without provisioning or managing servers, and only pay for the computing time you consume. API Gateway makes it easy to create and manage APIs that can be accessed by clients over the internet, with features such as authentication, rate limiting, and caching built in.

Top comments (0)