"Building a Serverless REST API with AWS Lambda, API Gateway, and DynamoDB Using Python"

pavan_s_7438006da5249fe71

Pavan S

Posted on October 27, 2024

"Building a Serverless REST API with AWS Lambda, API Gateway, and DynamoDB Using Python"

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

  1. Navigate to DynamoDB in the AWS Console and create a new table.
  2. Table Name: employee_info.
  3. Primary Key: employeeid (String).
  4. Attributes: Define fields such as name, department, position, and salary.

DynamoDB offers a highly scalable NoSQL solution perfect for handling unstructured employee data.

DynamoDB

Step 2: Create an IAM Policy

  1. Sign in to the AWS Management Console.
  2. Navigate to the IAM console.
  3. In the left navigation pane, click on Policies.
  4. Click on the Create policy button.
  5. ADD policy for Dynamodb

IAM

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)

lambda

Step 4: Create API Gateway Endpoints

Set Up API Gateway

  1. Go to API Gateway and create a REST API.
  2. 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.

API Gateway

Connect Methods to Lambda

For each HTTP method, connect the endpoint to the appropriate Lambda function.

Step 5: Deploy the API

  1. Create a Deployment Stage in API Gateway.
  2. Deploy the API to make the endpoints accessible.
  3. 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
  }

Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
pavan_s_7438006da5249fe71
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.

Related