
Building a Serverless REST API with AWS Lambda, API Gateway, and DynamoDB
Learn how to build a simple serverless REST API using Amazon API Gateway, AWS Lambda, and Amazon DynamoDB. This guide explains the architecture, implementation steps, and how these AWS services work together.
Building a Serverless REST API with AWS Lambda, API Gateway, and DynamoDB
Serverless architecture makes it possible to build and deploy applications without managing traditional servers. AWS provides several services that work together to create scalable and cost-efficient serverless applications.
In this article, we will build a simple REST API using Amazon API Gateway, AWS Lambda, and Amazon DynamoDB.
Architecture
Our application will follow this basic flow:
Client | vAmazon API Gateway | vAWS Lambda | vAmazon DynamoDBο»Ώ
The client sends an HTTP request to API Gateway. API Gateway invokes a Lambda function, and the Lambda function reads or writes data in DynamoDB.
AWS Services Used
1. Amazon API Gateway
Amazon API Gateway allows us to create and manage APIs that applications can use to communicate with backend services.
In this project, API Gateway will receive HTTP requests and trigger our Lambda function.
2. AWS Lambda
AWS Lambda lets us run code without provisioning or managing servers.
The Lambda function will contain the application logic. When an API request is received, Lambda executes the required operation.
3. Amazon DynamoDB
Amazon DynamoDB is a fully managed NoSQL database.
We can use DynamoDB to store application data without managing database servers.
Step 1: Create a DynamoDB Table
First, create a DynamoDB table.
For example, create a table named:
Usersο»Ώ
Use the following partition key:
userIdο»Ώ
The Β
userIdΒ will uniquely identify each user.Example item:
{ "userId": "101", "name": "Aditya", "email": "aditya@example.com"}ο»Ώ
Step 2: Create the Lambda Function
Create a new Lambda function from the AWS Lambda console.
For this example, we can use Python.
The Lambda function can receive an API request and store a user in DynamoDB.
Example:
import jsonimport boto3ο»Ώ
dynamodb = boto3.resource("dynamodb")table = dynamodb.Table("Users")ο»Ώ
def lambda_handler(event, context):ο»Ώ
body = json.loads(event.get("body", "{}"))ο»Ώ
user_id = body.get("userId") name = body.get("name") email = body.get("email")ο»Ώ
table.put_item( Item={ "userId": user_id, "name": name, "email": email } )ο»Ώ
return { "statusCode": 200, "headers": { "Content-Type": "application/json" }, "body": json.dumps({ "message": "User created successfully" }) }ο»Ώ
The function receives the request body, extracts the user information, and stores it in DynamoDB.
Step 3: Configure IAM Permissions
The Lambda function needs permission to access DynamoDB.
Create or attach an IAM role that allows the Lambda function to perform the required DynamoDB operations.
For this example, the function needs permission to write items to the Β
UsersΒ table.It is important to follow the principle of least privilege and grant only the permissions that the application actually needs.
Step 4: Create an API Gateway API
Next, create an API using Amazon API Gateway.
Create a route such as:
POST /usersο»Ώ
Connect this route to the Lambda function.
The request flow will now be:
POST /users | vAPI Gateway | vLambda | vDynamoDBο»Ώ
Step 5: Test the API
We can send a request to the API using tools such as Postman or cURL.
Example request:
curl -X POST https://your-api-url/users \-H "Content-Type: application/json" \-d '{ "userId": "101", "name": "Aditya", "email": "aditya@example.com"}'ο»Ώ
The Lambda function processes the request and stores the information in DynamoDB.
A successful response could look like:
{ "message": "User created successfully"}ο»Ώ
Understanding the Serverless Flow
The important part of this architecture is that we do not need to run or maintain a traditional web server.
When a request arrives:
- The client sends an HTTP request.
- API Gateway receives the request.
- API Gateway invokes the Lambda function.
- Lambda executes the application logic.
- Lambda communicates with DynamoDB.
- DynamoDB stores the data.
- Lambda returns a response.
- API Gateway sends the response back to the client.
Why Use Serverless?
Serverless architecture provides several advantages.
No server management
There is no need to manually provision or maintain EC2 servers for this application.
Automatic scaling
Lambda can automatically run additional function instances as the number of requests increases.
Pay for usage
With serverless services, costs are generally based on usage rather than keeping a server running continuously.
Faster development
Developers can focus on application logic instead of infrastructure management.
Security Considerations
Security should be considered when building a real-world API.
Some important improvements include:
- Use IAM policies with least-privilege permissions.
- Add authentication and authorization.
- Validate API input.
- Avoid storing sensitive information directly in source code.
- Use AWS Secrets Manager or Parameter Store for secrets when required.
- Enable logging and monitoring.
- Consider API throttling to protect the API from excessive requests.
Monitoring
AWS provides several services that can help monitor this architecture.
Amazon CloudWatch can be used to monitor Lambda execution, logs, errors, and performance.
API Gateway can also provide metrics that help identify request counts, latency, and errors.
Monitoring is especially important when moving a serverless application from development to production.
Possible Improvements
This basic application can be extended into a complete serverless backend.
For example, we could add:
POST /usersGET /users/{id}PUT /users/{id}DELETE /users/{id}ο»Ώ
We could also add authentication using Amazon Cognito and introduce additional Lambda functions for different API operations.
A production architecture could look like:
βββββββββββββββββββ β Client β ββββββββββ¬βββββββββ β v βββββββββββββββββββ β API Gateway β ββββββββββ¬βββββββββ β v βββββββββββββββββββ β AWS Lambda β ββββββββββ¬βββββββββ β v βββββββββββββββββββ β DynamoDB β βββββββββββββββββββο»Ώ
Additional services such as Amazon Cognito, Amazon CloudWatch, and AWS IAM can be added depending on the application's requirements.
Conclusion
AWS Lambda, Amazon API Gateway, and Amazon DynamoDB provide a simple way to build a serverless backend without managing traditional servers.
By combining these services, we can create APIs that are scalable, event-driven, and easier to maintain.
This architecture is a useful starting point for developers who want to learn how AWS serverless services work together and build cloud-native applications.
The same approach can be extended to larger applications by adding authentication, additional API routes, monitoring, automated deployments, and other AWS services.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article