"Building a Serverless REST API with AWS Lambda, API Gateway, and DynamoDB Using Python"
Pavan S
Posted on October 27, 2024
Overview
In this project, I developed a serverless REST API using AWS Lambda, API Gateway, and DynamoDB. The API enables CRUD operations on employee records, demonstrating how to leverage AWS's serverless architecture to build scalable, cost-effective applications.
Tech Stack
- AWS Lambda: Executes CRUD functions without the need for server management.
- API Gateway: Routes HTTP requests to specific Lambda functions.
- DynamoDB: Stores employee records in a NoSQL database.
- Python (boto3): Handles the application logic and database operations.
Step-by-Step Project Setup
Step 1: Set Up DynamoDB Table
- Navigate to DynamoDB in the AWS Console and create a new table.
-
Table Name:
employee_info
. -
Primary Key:
employeeid
(String). -
Attributes: Define fields such as
name
,department
,position
, andsalary
.
DynamoDB offers a highly scalable NoSQL solution perfect for handling unstructured employee data.
Step 2: Create an IAM Policy
- Sign in to the AWS Management Console.
- Navigate to the IAM console.
- In the left navigation pane, click on Policies.
- Click on the Create policy button.
- ADD policy for Dynamodb
Step 3: Write the Lambda Function Code
Create a Lambda function in Python that will handle requests for:
- Retrieving all employees or a specific employee (
GET
). - Adding a new employee (
POST
). - Updating an employee's details (
PATCH
). - Deleting an employee record (
DELETE
)
Step 4: Create API Gateway Endpoints
Set Up API Gateway
- Go to API Gateway and create a REST API.
- Define Resources and Methods:
-
/employee:
-
GET
- Retrieve employee data. -
POST
- Add new employee. -
PATCH
- Update existing employee data. -
DELETE
- Remove an employee record.
-
-
/employees:
-
GET
- Retrieve all employees.
-
-
/Status:
-
GET
- Retrieve all employees Status.
-
-
/employee:
Connect Methods to Lambda
For each HTTP method, connect the endpoint to the appropriate Lambda function.
Step 5: Deploy the API
- Create a Deployment Stage in API Gateway.
- Deploy the API to make the endpoints accessible.
- Note the endpoint URL generated by API Gateway; this will serve as the base URL for the REST API.
Example Requests
-
GET
/employee?employeeid=123
Retrieves data for employee with ID 123.
-
POST
/employee
Adds a new employee.
Body:
json
{
"employeeid": "123",
"name": "John Doe",
"position": "Engineer",
"salary": 60000
}
💖 💪 🙅 🚩
Pavan S
Posted on October 27, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.