Day 1: Deploying a Serverless API on AWS Lambda

Overview:
In this tutorial, we’ll walk you through the steps to build and deploy a serverless REST API using AWS Lambda, API Gateway, and a simple Node.js function. AWS Lambda allows you to run code without provisioning or managing servers, making it a perfect choice for serverless applications.

By the end of this guide, you’ll have a fully functional API endpoint that you can call from a browser or a REST client like Postman.


Prerequisites:

  • AWS Account (You can create one here).
  • Basic knowledge of Node.js.
  • Installed AWS CLI on your local machine (instructions here).

Step 1: Setting Up AWS CLI

To interact with AWS services, you need to configure AWS CLI on your machine. Run the following command to set up the credentials:

aws configure

It will prompt you to enter the following:

  • AWS Access Key ID
  • AWS Secret Access Key
  • Default region name (e.g., us-east-1)
  • Default output format (e.g., json)

Step 2: Creating Your Lambda Function

2.1 Write Your Lambda Code

In this tutorial, we’ll create a simple Lambda function using Node.js that returns a JSON response.

Create a folder called lambda-api and a file called index.js inside that folder. This will be the Lambda function’s code.

mkdir lambda-api
cd lambda-api
touch index.js

Add the following code to index.js:

exports.handler = async (event) => {
    const response = {
        statusCode: 200,
        body: JSON.stringify({
            message: 'Hello from AWS Lambda!',
            input: event,
        }),
    };
    return response;
};

This Lambda function simply returns a JSON response with a “Hello from AWS Lambda!” message and the input event data.

See also  Part 5: Monitoring and Optimizing Server Performance with AWS CloudWatch

2.2 Create a ZIP File for the Lambda Function

Before uploading the Lambda function, you need to zip the index.js file:

zip -r lambda-api.zip index.js

Step 3: Create a Lambda Function via AWS Console

  1. Log in to AWS Management Console:
    Go to the AWS Lambda Console.
  2. Create Function:
  • Click on Create Function.
  • Choose Author from Scratch.
  • Set Function name to my-lambda-api.
  • Set Runtime to Node.js 18.x (or any version that suits you).
  • Choose Create a new role with basic Lambda permissions. Click Create Function.
  1. Upload Your Code:
  • Scroll down to the Code source section.
  • Under Actions, click Upload a .zip file.
  • Upload the lambda-api.zip file you created earlier.
  1. Save and Deploy:
    Once your code is uploaded, click Deploy.

Step 4: Create an API Gateway

To access the Lambda function via HTTP, we need to create an API Gateway.

  1. Go to API Gateway Console:
    Visit the API Gateway Console.
  2. Create an API:
  • Click on Create API.
  • Select HTTP API.
  • Click Build.
  1. Configure API:
  • For Integration, choose Lambda.
  • Select the Lambda function you created (my-lambda-api).
  • For Security, choose Open (for simplicity; for production, you would likely secure this API).
  • Click Next.
  1. Configure Routes:
  • For Method, choose ANY.
  • For Resource Path, enter /api.
  • Click Next.
  1. Deploy API:
  • Review your settings.
  • Click Create and Deploy.

Once the deployment is done, you will see the Invoke URL. This is your API endpoint that calls the Lambda function.

Example:
https://abc123.execute-api.us-east-1.amazonaws.com


Step 5: Testing the API

You can test the API by making a GET request using your browser or any REST client like Postman. Here’s how to do it with curl:

curl https://abc123.execute-api.us-east-1.amazonaws.com/api

You should see a response like this:

{
  "message": "Hello from AWS Lambda!",
  "input": {}
}

Step 6: Adding Environment Variables (Optional)

If you want to add environment-specific settings (like database credentials or API keys), you can add environment variables to the Lambda function.

  1. Go to your Lambda Function:
    In the Lambda Console, navigate to your function my-lambda-api.
  2. Add Environment Variables:
  • Under the Configuration tab, click Environment Variables.
  • Click Edit and add key-value pairs for your variables.
  1. Accessing Environment Variables in Code:
    You can access these variables inside the Lambda function like this:
const myVar = process.env.MY_ENV_VARIABLE;

Step 7: Setting Up CORS

To allow other domains (e.g., a web app) to make requests to your API, you need to enable CORS (Cross-Origin Resource Sharing).

  1. Go to API Gateway:
    Open your API in the API Gateway Console.
  2. Enable CORS:
  • Select your API route (e.g., /api).
  • Click on CORS under Actions.
  • Select the default options and click Enable CORS.
See also  Building a Smart Search Engine with PHP (Simplified Approach)

Step 8: Cleaning Up Resources

Once you’re done testing, you should clean up the resources to avoid incurring costs.

  1. Delete the Lambda Function:
    Go to the Lambda Console, select your function, and click Delete.
  2. Delete the API Gateway:
    Go to the API Gateway Console, select your API, and click Delete API.

Conclusion

In this tutorial, you learned how to deploy a serverless API using AWS Lambda and API Gateway. You wrote a simple Node.js Lambda function, configured an API Gateway to handle HTTP requests, and tested the API endpoint. This setup is an excellent starting point for building scalable serverless applications in the cloud.

For more advanced usage, you can integrate AWS DynamoDB for data storage or set up authentication using AWS Cognito.


Next Steps:
Consider adding additional endpoints and logic to handle POST, PUT, and DELETE methods, or integrating with other AWS services like DynamoDB or S3.


Feel free to copy and paste the code and configurations directly into your project to try it out!

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.