REST API with Lambda
×


REST API with Lambda

189

🔧 REST API with Lambda: A Serverless Approach

Serverless REST APIs are becoming the new norm for modern cloud-native applications. By leveraging AWS Lambda with Amazon API Gateway, developers can deploy scalable, cost-effective APIs without managing servers. This blog covers how to build a simple REST API using AWS Lambda, including setup, endpoints, and best practices.

🌐 What is a REST API with Lambda?

A REST API with Lambda means exposing AWS Lambda functions as HTTP endpoints using Amazon API Gateway. When a client sends a request (like GET or POST), the API Gateway triggers the corresponding Lambda function, which processes the request and returns a response.

📦 Basic Use Case: Book Management API

Let’s say we want to create a simple API to manage books with the following endpoints:

  • GET /books – Fetch all books
  • GET /books/{id} – Fetch a specific book
  • POST /books – Add a new book
  • DELETE /books/{id} – Delete a book

🧪 Lambda Function Example (Node.js)

This sample Lambda handles a GET request to return a list of books:

exports.handler = async (event) => {
    const books = [
        { id: 1, title: "1984", author: "George Orwell" },
        { id: 2, title: "Brave New World", author: "Aldous Huxley" }
    ];

    return {
        statusCode: 200,
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(books)
    };
};

🚀 Steps to Build REST API with Lambda

  1. Create an AWS Lambda function using the AWS Console or CLI.
  2. Write the business logic to handle requests.
  3. Open Amazon API Gateway and create a new HTTP or REST API.
  4. Define routes like /books or /books/{id}.
  5. Link each route and method (GET, POST, etc.) to your Lambda function.
  6. Deploy the API to a stage (e.g., dev or prod).

⚙️ Sample API Gateway Integration

Here’s how to connect the Lambda function with a GET endpoint in API Gateway:

# AWS CLI command to create API

aws apigateway create-rest-api --name "BookAPI"

# Then, create resources and methods using AWS Console or SDK

# Example integration configuration (simplified)
{
  "integrationHttpMethod": "POST",
  "type": "AWS_PROXY",
  "uri": "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/<Lambda-ARN>/invocations"
}

🧰 Example POST Lambda for Adding Books

This example reads the POST body and adds a new book entry (mocked):

exports.handler = async (event) => {
    const data = JSON.parse(event.body);
    const newBook = {
        id: Math.floor(Math.random() * 1000),
        title: data.title,
        author: data.author
    };

    return {
        statusCode: 201,
        body: JSON.stringify({ message: "Book added", book: newBook })
    };
};

🔐 Enabling CORS

If you plan to call your Lambda-backed API from a browser (especially from another domain), you need to enable CORS:

return {
    statusCode: 200,
    headers: {
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Headers": "Content-Type",
        "Access-Control-Allow-Methods": "GET, POST, DELETE"
    },
    body: JSON.stringify(response)
};

📊 Logging and Monitoring

Every Lambda function can automatically push logs to CloudWatch. Make sure to include logs in your code:

console.log("Incoming request:", JSON.stringify(event));

Use AWS CloudWatch for dashboards, alerts, and metrics related to API invocations, errors, and performance.

🛡️ IAM Roles for Security

Ensure your Lambda function has the correct IAM execution role to perform tasks like reading from databases or accessing other AWS services.

{
  "Effect": "Allow",
  "Action": ["dynamodb:PutItem", "dynamodb:GetItem"],
  "Resource": "arn:aws:dynamodb:us-east-1:123456789012:table/Books"
}

✅ Pros of Using Lambda for REST APIs

  • No infrastructure to manage
  • Scales automatically
  • Pay-per-invocation pricing
  • Event-driven design fits API use cases perfectly

⚠️ Considerations

  • Cold starts can introduce latency
  • Testing and debugging may require mock setups
  • Request/response size limits (6 MB max for Lambda payload)

🎯 Final Thoughts

REST API with Lambda is a powerful pattern for building scalable, lightweight web services. It removes the burden of server management and shifts the focus to writing business logic. With tools like API Gateway, CloudWatch, and IAM, you can build production-ready APIs entirely in the serverless realm. Whether you're crafting a CRUD backend, a webhook handler, or a microservice endpoint—Lambda has you covered.



If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!

For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!


Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments

Coding Tag WhatsApp Chat