Last modified: Jan 01, 2026 By Alexander Williams
Build Serverless APIs with AWS API Gateway and Python
Serverless computing changes how we build apps. You no longer manage servers. AWS handles the infrastructure for you. This guide shows you how to build a serverless API.
We will use AWS API Gateway and Python. This combo is powerful for creating scalable backends. It is also very cost-effective for variable traffic.
What is a Serverless API?
A serverless API runs without dedicated servers. You write code for individual functions. AWS Lambda executes this code on demand.
AWS API Gateway is the front door. It receives HTTP requests and routes them to your Lambda functions. You pay only for the compute time you use.
This model is perfect for APIs with unpredictable traffic. It scales automatically. There is zero idle cost.
Why Use API Gateway and Python?
AWS API Gateway is a fully managed service. It handles all tasks like traffic management and authorization. It also provides monitoring and API versioning.
Python is a great choice for Lambda. It is easy to write and read. The AWS SDK for Python, called Boto3, is very robust. You can use it to interact with other AWS services.
For example, your API could process data and store it in S3. You might want to read our guide on how to Manage AWS S3 Buckets with Python Boto3.
Prerequisites
You need an AWS account. Basic knowledge of Python and REST APIs is helpful. You should also have the AWS CLI installed and configured.
It's a good idea to understand Boto3 basics. Our article on Getting Started with AWS SDK for Python Boto3 can help.
Step 1: Create a Python Lambda Function
First, we write the business logic. Create a new Python file called `lambda_function.py`. This will be our handler.
The function must accept an `event` and `context` parameter. The `event` contains the request data from API Gateway.
import json
def lambda_handler(event, context):
"""
A simple Lambda function that returns a greeting.
The event parameter holds the HTTP request data.
"""
# Extract query string parameters from the event
query_params = event.get('queryStringParameters', {})
# Get the 'name' parameter, default to 'World'
name = query_params.get('name', 'World')
# Create the response body
body = {
"message": f"Hello, {name}!",
"input": event
}
# Return a proper API Gateway response
response = {
"statusCode": 200,
"headers": {
"Content-Type": "application/json"
},
"body": json.dumps(body)
}
return response
The lambda_handler is the entry point. It reads a 'name' from the query string. It then returns a JSON greeting message.
The response format is crucial. API Gateway expects a dictionary with `statusCode`, `headers`, and `body`. The body must be a JSON string.
Step 2: Deploy the Lambda Function
Now, deploy this code to AWS Lambda. You can use the AWS Console, CLI, or an infrastructure-as-code tool.
Zip your `lambda_function.py` file. Then create a new Lambda function from the AWS Console. Choose Python as the runtime.
Upload the zip file as your function code. Set the handler to `lambda_function.lambda_handler`. For detailed steps, see our Deploy Python Apps on AWS Lambda Guide.
Remember to set up proper IAM permissions. Your Lambda function's execution role needs basic logging permissions.
Step 3: Set Up API Gateway
Go to the API Gateway service in AWS Console. Click "Create API". Choose the "REST API" type (for this example).
Create a new resource, for example, `/hello`. Then create a `GET` method on this resource.
In the method setup, choose "Lambda Function" as the integration type. Select the region and type the name of your Lambda function.
API Gateway will ask for permission to invoke the Lambda. Grant it. Your API is now connected to your Python code.
Step 4: Deploy and Test the API
Before testing, you must deploy the API. Create a new deployment stage, like `prod` or `dev`.
After deployment, API Gateway gives you an invoke URL. It looks like `https://abc123.execute-api.region.amazonaws.com/dev`.
Test your `/hello` endpoint. Use a browser or a tool like `curl`.
# Test without a name parameter
curl https://abc123.execute-api.us-east-1.amazonaws.com/dev/hello
# Test with a name parameter
curl "https://abc123.execute-api.us-east-1.amazonaws.com/dev/hello?name=Developer"
You should see JSON responses. The first call greets "World". The second greets "Developer".
Advanced: Handling POST Requests and JSON Body
Let's extend our API to handle POST requests. This is common for creating data. Update your Lambda function.
import json
def post_handler(event, context):
"""
Handles POST requests with a JSON body.
"""
# Parse the JSON body from the request
try:
request_body = json.loads(event.get('body', '{}'))
except json.JSONDecodeError:
request_body = {}
# Extract data from the parsed body
user_id = request_body.get('user_id', 0)
data = request_body.get('data', '')
# Simulate some processing (e.g., save to a database)
# In a real app, you might call another service here.
processed_data = f"Processed: {data} for user {user_id}"
# Create the response
response_body = {
"status": "success",
"processed_message": processed_data,
"received": request_body
}
return {
"statusCode": 200,
"headers": {"Content-Type": "application/json"},
"body": json.dumps(response_body)
}
Create a `POST` method on your API resource. Link it to this new handler or a unified handler that routes based on `event['httpMethod']`.
For complex routing, consider using a framework like FastAPI with Mangum. Learn more in our guide Deploy FastAPI to AWS Lambda with Mangum.
Best Practices and Tips
Use Environment Variables. Never hardcode secrets. Use Lambda environment variables for configuration.
Enable Logging. Use Amazon CloudWatch. Print logs with Python's `print` statement. They will appear in CloudWatch Logs.
Optimize Cold Starts. Keep your deployment package small. Use Lambda Layers for common dependencies. Avoid large Python libraries if possible.
Set Timeouts and Memory. Configure your Lambda function's timeout and memory settings appropriately. A simple API might need only 128 MB and a 3-second timeout.
Secure Your API. Use API Gateway features like API keys, IAM authorization, or Cognito user pools to protect your endpoints.
Conclusion
Building serverless APIs with AWS API Gateway and Python is straightforward. It offers immense scalability and cost savings.
You start by writing a Python Lambda function. Then you expose it via API Gateway. The integration is seamless.
This architecture lets you focus on code, not servers. You can easily connect your API to other AWS services like DynamoDB or S3.
Start with a simple GET endpoint. Then expand to POST, authentication, and more. The serverless world is ready for your ideas.