Building a Serverless API with AWS API Gateway and AWS Lambda in Node.js

Umar Farooque Khan
5 min readNov 12, 2023

--

Building a Serverless API with AWS API Gateway and AWS Lambda in Node.js

In the ever-evolving landscape of cloud computing, serverless architecture has gained significant popularity. AWS (Amazon Web Services) provides a robust set of tools and services to help developers build serverless applications effortlessly. In this article, we’ll explore how to create a serverless API using AWS API Gateway and AWS Lambda with Node.js, empowering you to build scalable and cost-effective APIs.

Why Serverless APIs?

Traditional web applications often require you to manage and scale servers, which can be complex and costly. Serverless APIs offer an alternative approach, where you can focus on writing code while AWS handles the infrastructure management. Here are some key benefits of serverless APIs:

  1. Auto-scaling: Serverless APIs automatically scale based on incoming traffic, ensuring performance under heavy loads.
  2. Cost-Efficiency: You only pay for the compute time your API consumes, making it cost-effective for smaller projects.
  3. Easy Maintenance: No server management means you can focus on your code and not worry about patching or maintaining the underlying infrastructure.
  4. Flexibility: Serverless APIs are highly flexible, allowing you to choose the programming language that suits your project, such as Node.js, Python, or Java.

Let’s dive into building a serverless API using Node.js with AWS Lambda and API Gateway.

Prerequisites

Before we get started, make sure you have the following prerequisites in place:

  1. AWS Account: You need an AWS account to use AWS services.
  2. Node.js: Ensure you have Node.js installed on your local machine.
  3. AWS CLI: Install and configure the AWS Command Line Interface (CLI).
  4. Serverless Framework (Optional): While not required, the Serverless Framework is a helpful tool for deploying serverless applications.

Setting Up Your Environment

AWS Lambda Function

First, we’ll create an AWS Lambda function in Node.js that will serve as the core of our serverless API. For this example, let’s create a simple function that returns a greeting:

exports.handler = async (event) => {
return {
statusCode: 200,
body: JSON.stringify({ message: 'Hello, Serverless API!' }),
};
};

You can use the AWS Management Console or the Serverless Framework to deploy this function.

AWS API Gateway

Next, we’ll set up the AWS API Gateway to act as the front-end for our serverless API:

  1. Log in to the AWS Management Console.
  2. Navigate to the API Gateway service.
  3. Click “Create API” and choose “HTTP API.”
  4. Configure your HTTP API. Give it a name and, under “CORS,” you can enable Cross-Origin Resource Sharing if your API will be accessed from a web browser.
  5. Click “Create API.”
  6. Under the “Routes” section, create a new route and associate it with the Lambda function you created earlier.
  7. Deploy the API by creating a new stage. Stages allow you to manage different versions of your API, such as development, testing, or production.

Testing Your API

Once you’ve created your API, you can test it by clicking on the stage and copying the API endpoint URL. You can use tools like Postman or curl to send requests to your serverless API.

For example, you can send a GET request to your API’s endpoint:

curl https://your-api-endpoint-url

You should receive a response with a status code of 200 and the message “Hello, Serverless API!”.

Securing Your Serverless API

Security is a crucial aspect of any API. With AWS API Gateway, you can set up various security mechanisms, such as API keys, IAM (Identity and Access Management) authorization, and custom authorizers to control who can access your API. You can also use AWS Cognito for user authentication.

For example, to secure your API using an API key, you can:

  1. In the API Gateway console, select your API.
  2. Under “Stages,” create a new stage, if you haven’t already.
  3. Under “Settings,” you can enable API key source and set a stage variable for the API key.
  4. Deploy the updated API.

Now, to access your API, you’ll need to include the API key as a header in your requests. You can manage API keys in the AWS Management Console.

Handling Request Data

Serverless APIs often need to process incoming data. In Node.js, you can access request data from the event object passed to your Lambda function.

For example, to handle a POST request with JSON data, you can modify your Lambda function as follows:

exports.handler = async (event) => {
const requestBody = JSON.parse(event.body);
// Process the data from the request
const name = requestBody.name;
return {
statusCode: 200,
body: JSON.stringify({ message: `Hello, ${name}!` }),
};
};

This code parses the JSON request body and extracts the name property to personalize the response.

Logging and Monitoring

It’s essential to set up proper logging and monitoring for your serverless API. AWS CloudWatch provides tools for monitoring your Lambda function’s performance, tracking errors, and collecting custom logs.

You can use the console object to log messages within your Lambda function. These messages will be available in the CloudWatch logs for debugging and monitoring.

Custom Domains

AWS API Gateway allows you to set up custom domains for your serverless API, giving it a more branded and user-friendly URL. This can be especially useful if you want to provide a clean and easily recognizable endpoint for your users.

To set up a custom domain, follow these steps:

  1. Register a domain or configure an existing one to point to AWS Route 53.
  2. In the API Gateway console, select your API and click on “Custom domain names.”
  3. Create a new custom domain and associate it with your API.
  4. Configure the base path mapping to route your API requests to the correct stage.
  5. Obtain an SSL/TLS certificate for your domain. AWS provides free certificates via AWS Certificate Manager.
  6. Associate the certificate with your custom domain.

Now, your serverless API can be accessed using your custom domain, providing a more professional and user-friendly experience.

Deploying and Scaling

With serverless architecture, scaling is effortless. AWS Lambda and API Gateway automatically handle the scaling of your API based on the incoming traffic. You don’t need to worry about provisioning additional servers or managing the infrastructure.

To deploy updates to your serverless API, you can use the Serverless Framework or the AWS Management Console. The Serverless Framework provides a straightforward way to define and deploy your API resources using a configuration file.

Conclusion

Building a serverless API with AWS API Gateway and AWS Lambda in Node.js is a powerful way to create scalable, cost-effective, and easily maintainable APIs. With AWS handling the infrastructure and scaling, you can focus on writing code that meets your business requirements.

In this article, we covered the fundamentals of setting up a serverless API, securing it with API keys, handling request data, and configuring custom domains.

--

--

Umar Farooque Khan
Umar Farooque Khan

Written by Umar Farooque Khan

Experienced software developer with a passion for clean code and problem-solving. Full-stack expertise in web development. Lifelong learner and team player.

No responses yet