Serverless API Deployment with AWS Lambda and API Gateway
Published: 2023-02-26 16:24:45

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j8wxmi0q5f12gxbp7040.png)
1.Choose to Create a function
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/adubmmcdvq0ad683wf5u.png)
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2i7mao10o9cqmu4vffvx.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r79kak8qr3jh3ypyunuk.png)
● You will see a page similar to the page below

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/il3hpc3455xtum70ygzf.png)
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kkvowvttgariw58vilba.png)
● The code looks like this

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ffdpjyifugwxomtf14hj.png)
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4x2f7qiiie4r0wjjx8ro.png)

5. Create a test event

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aii2o16h6o8cm29e6s4g.png)
● You will get an error as shown:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fz80tdupsjgj6ui0sh7s.png)
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.
6. 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0bmtx35fndbl21iy9uq8.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2ujptof5awup0fou3s8n.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x1dt6psq18eq0htdn0fu.png)
● 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/osv4ai592gogmqhoob15.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rt9k2h94aj3tqy0gsu62.png)

1.Test the lambda function

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3jtz0uely85jwy9eo1va.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/79ayfqs7mf0gj0mbl5x7.png)
Now the code is successfully executed.
1.Create an API Gateway
● Goto AWS Management Console and navigate the API Gateway service

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ss7zoos7hmfuj18jhiwh.png)
Choose REST API

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qknlkbz1six3fo1llx10.png)
● Create API

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lbfyn9o5ale5ekcl7tuh.png)
●Goto actions and Create Method

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i4xpldk4vohbo9o3fb7b.png)
●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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k0you87xsn1t7y3oaufd.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mw87xl0vw9wb1isxgrkm.png)

● Add Permission to Lambda Function

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4y8gci3w9qkcvg7ajcf6.png)
Test 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mvtu36baemexmflvjwo3.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/12hy0v3bxkfs3bfbwuv7.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tegxfykyjk7xel6tenow.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k6fd53qud6ac6s5e9zm5.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ju6wp724kbojszyp2n8p.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2fcwqhjy9godb0cjewdz.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qedzo4s2gxiakq68eoo8.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wt1at78a3j8egbp7pyhy.png)
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ud970tqs26yh3032i24s.png)
-Set trigger configuration as shown below

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rqqk7shk2eaed7ukklqy.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l6xonvpxe88r3mvgiwrd.png)
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.