AWS Builder Center

Building a Serverless API with AWS Lambda and Amazon API Gateway

Learn how to build a simple serverless HTTP API using AWS Lambda and Amazon API Gateway without managing servers. This hands-on guide covers creating, testing, deploying, and securing a Lambda-based application using AWS best practices.

Introduction

Modern applications often need backend functionality without the complexity of managing servers. AWS Lambda makes this possible by allowing developers to run code without provisioning or maintaining servers.
In this tutorial, we will build a simple serverless API using AWS Lambda and Amazon API Gateway. The API will receive an HTTP request, execute a Lambda function, and return a response.
By the end of this tutorial, you will understand how Lambda works, how to create a function, connect it to API Gateway, and test the resulting serverless API.

What is AWS Lambda?

AWS Lambda is a serverless compute service that runs your code in response to events.
Instead of running an application continuously on a virtual machine, you upload your function code to Lambda. AWS automatically handles the underlying infrastructure and runs your function when it is invoked.
Lambda can be triggered by many AWS services and applications, including:
  • Amazon API Gateway
  • Amazon S3
  • Amazon EventBridge
  • Amazon SQS
  • Amazon SNS
  • Amazon DynamoDB
  • Scheduled events
This event-driven architecture makes Lambda useful for APIs, automation, data processing, scheduled jobs, and many other workloads.

Architecture

Our application will use the following flow:
Client → API Gateway → AWS Lambda → Response
When a client sends an HTTP request:
  1. API Gateway receives the request.
  1. API Gateway invokes the Lambda function.
  1. Lambda executes the function code.
  1. Lambda returns the result to API Gateway.
  1. API Gateway sends the response back to the client.

Prerequisites

Before starting, you need:
  • An AWS account
  • Basic knowledge of AWS
  • Basic programming knowledge
  • Access to the AWS Management Console
No server or virtual machine is required.

Step 1: Create a Lambda Function

Open the AWS Management Console and navigate to AWS Lambda.
Choose Create function.
Select:
Author from scratch
For the function configuration, use values similar to:
  • Function name:  hello-serverless 
  • Runtime:  Python 3.x 
  • Architecture:  x86_64 
Then choose Create function.
Lambda creates the function and provides an execution environment for your code.

Step 2: Add the Lambda Code

Replace the default function code with the following Python example:
import json

def lambda_handler(event, context):
return {
"statusCode": 200,
"headers": {
"Content-Type": "application/json"
},
"body": json.dumps({
"message": "Hello from AWS Lambda!",
"success": True
})
}

Choose Deploy to save the changes.
This function returns an HTTP status code of  200  and a JSON response.

Step 3: Test the Lambda Function

Before connecting Lambda to API Gateway, you can test the function directly.
Choose Test and create a new test event.
For this simple example, the contents of the event are not important because the function does not use the incoming event.
Run the test.
You should see a response similar to:
{
"statusCode": 200,
"body": "{\"message\": \"Hello from AWS Lambda!\", \"success\": true}"
}

This confirms that the Lambda function is working.

Step 4: Create an API Gateway Trigger

Now we will expose the Lambda function through an HTTP endpoint.
Return to the Lambda function and choose Add trigger.
Select:
API Gateway
For the API configuration, choose an HTTP API.
You can allow the API to be publicly accessible for this demonstration, but for production applications you should configure appropriate authentication and authorization.
Create the trigger.
API Gateway will provide an HTTP endpoint for your Lambda function.

Step 5: Test the API

Copy the API endpoint provided by API Gateway and open it in a browser or use a command such as:
curl https://your-api-id.execute-api.region.amazonaws.com

The API should return:
{
"message": "Hello from AWS Lambda!",
"success": true
}

You have now created a serverless API without provisioning a server.

Understanding the Lambda Handler

The following line defines the Lambda handler:
def lambda_handler(event, context):

The  event  parameter contains information about the event that triggered the function.
For an API Gateway request, the event can contain information such as the HTTP method, path, headers, query parameters, and request body.
The  context  parameter provides information about the Lambda execution environment, including the remaining execution time and request information.
Understanding the event structure becomes especially important when building production APIs.

Why Use Lambda?

AWS Lambda provides several advantages.

No Server Management

You don't need to provision, patch, or maintain servers for your function.

Automatic Scaling

Lambda can automatically scale your function based on incoming requests.

Pay for Usage

With Lambda's request-based pricing model, you generally pay based on the number of requests and compute duration rather than keeping a server running continuously.

Easy AWS Integration

Lambda integrates with many AWS services, making it useful for event-driven architectures.

Best Practices

When building production Lambda applications, consider the following practices.

Keep Functions Small

A Lambda function should ideally have a clear and focused responsibility.
Instead of putting an entire application into one function, separate independent pieces of functionality where appropriate.

Reuse Connections

If your function connects to databases or other services, initialize reusable connections outside the handler when appropriate. This can reduce unnecessary initialization during warm invocations.

Use Environment Variables

Do not hard-code configuration values in your source code.
Lambda environment variables can be used for configuration such as:
TABLE_NAME=Users
ENVIRONMENT=production

For sensitive values, use services such as AWS Secrets Manager rather than storing secrets directly in environment variables.

Monitor Your Functions

Use Amazon CloudWatch to monitor Lambda logs, metrics, and errors.
Monitoring helps you identify problems such as:
  • Function errors
  • High execution duration
  • Unexpected invocation rates
  • Timeout problems

Security Considerations

Security should be considered from the beginning.
Use AWS IAM to give Lambda only the permissions it needs.
For example, if a function only needs to read from an S3 bucket, its execution role should not have unnecessary permissions to modify other AWS resources.
For APIs, consider authentication and authorization requirements before exposing endpoints publicly.
Avoid placing AWS access keys or passwords directly inside Lambda source code.

Common Use Cases

AWS Lambda can be used for many different workloads, including:
  • REST and HTTP APIs
  • Image and file processing
  • Scheduled automation
  • Log processing
  • Data transformation
  • Backend services for web and mobile applications
  • Event-driven workflows
  • Serverless applications
For example, an S3 upload can trigger a Lambda function that processes an image automatically.

Conclusion

AWS Lambda provides a simple way to run application code without managing servers.
By combining Lambda with API Gateway, we can create scalable HTTP APIs using a small amount of code. The serverless approach allows developers to focus on application logic while AWS manages the underlying compute infrastructure.
The example in this article is intentionally simple, but the same architecture can be extended with services such as Amazon DynamoDB, Amazon S3, Amazon SQS, Amazon EventBridge, and other AWS services.
If you are beginning your serverless journey, building a small Lambda API is a good way to understand event-driven architecture and the fundamentals of AWS serverless computing.
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article