Using AWS Lambda as a REST API Endpoint
AWS Lambda provides a convenient way to build REST API endpoints without managing servers. It allows developers to run application code in response to HTTP requests while AWS takes care of the underlying infrastructure, scaling, and availability.
How It Works
A common architecture combines Amazon API Gateway with AWS Lambda. API Gateway receives HTTP requests and routes them to the appropriate Lambda function. The function processes the request, performs the required business logic, and returns an HTTP response.
The typical request flow looks like this:
Client Application | | HTTP Request v Amazon API Gateway | | Lambda Proxy Integration v AWS Lambda | | Business Logic v Database / AWS Services | v HTTP Response | v ClientFor example, a REST API for managing users might expose the following endpoints:
Method | Endpoint | Description |
|---|---|---|
GET | /users | Retrieve all users |
GET | /users/{id} | Retrieve a specific user |
POST | /users | Create a user |
PUT | /users/{id} | Update a user |
DELETE | /users/{id} | Delete a user |
Each endpoint can invoke a dedicated Lambda function, or multiple routes can be handled by one function that dispatches requests based on the HTTP method and path.
Example Implementation
Let's create a simple REST API using Amazon API Gateway and an AWS Lambda function written in Python.
The example will expose a GET endpoint:
GET /hello?name=John The Lambda function will return a JSON response:
{ "message": "Hello, John!"}Step 1: Implement the Lambda function
Create a file named
app.py :import json
def handler(event, context): # Read query string parameters params = event.get("queryStringParameters") or {} name = params.get("name", "world")
# Prepare HTTP response response = { "statusCode": 200, "headers": { "Content-Type": "application/json" }, "body": json.dumps({ "message": f"Hello, {name}!" }) }
return responseThe function receives an event object containing information about the incoming HTTP request. With Lambda Proxy Integration, API Gateway passes request details such as HTTP method, headers, query parameters, and request body to the function.
The Lambda function returns an object containing an HTTP status code, response headers, and a serialized response body.
Step 2: Configure API Gateway integration
In Amazon API Gateway, create a REST API and configure a resource and method:
- Resource:
/hello
- HTTP method:
GET
- Integration type: Lambda Function
- Lambda Proxy Integration: Enabled
- Lambda function: The function created in Step 1
Lambda Proxy Integration allows API Gateway to pass the HTTP request directly to Lambda and forward the function's response to the client.
Step 3: Grant API Gateway permission to invoke Lambda
API Gateway needs explicit permission to invoke the Lambda function.
This permission is configured through the Lambda function's resource-based policy. It allows the API Gateway service principal to execute the
lambda:InvokeFunction action.For an existing API configured manually, the permission can be added using the AWS CLI:
aws lambda add-permission \ --function-name HelloFunction \ --statement-id AllowApiGatewayInvoke \ --action lambda:InvokeFunction \ --principal apigateway.amazonaws.com \ --source-arn \ "arn:aws:execute-api:REGION:ACCOUNT_ID:API_ID/*/GET/hello"Replace the placeholders with your AWS Region, account ID, and API Gateway API ID.
The
source-arn restricts invocation permission to the specified API, HTTP method, resource, and stages.It is generally preferable to grant access to specific API resources rather than using an unrestricted wildcard.
Step 4: Configure Lambda execution permissions
There are two different permission mechanisms involved in this architecture:
1. Lambda resource-based policy
Controls which services or accounts can invoke the Lambda function.
For this example, it allows:
- Principal:
apigateway.amazonaws.com
- Action:
lambda:InvokeFunction
2. Lambda execution role
Controls which AWS resources the Lambda function itself can access.
Every Lambda function requires an execution role. At a minimum, it should have permission to write logs to Amazon CloudWatch.
For example, the AWS managed policy
AWSLambdaBasicExecutionRole provides the required basic logging permissions.If the function needs to access DynamoDB, S3, or other AWS services, additional permissions should be attached to its execution role. These should follow the principle of least privilege.
API Gateway does not need general access to the Lambda execution role when using the resource-based permission approach described above.
Step 5: Deploy the API using AWS SAM
Instead of configuring all resources manually, AWS Serverless Application Model (SAM) can define the Lambda function and API Gateway integration using infrastructure as code.
An example
template.yaml :AWSTemplateFormatVersion: '2010-09-09'Transform: AWS::Serverless-2016-10-31
Resources: HelloFunction: Type: AWS::Serverless::Function Properties: Runtime: python3.12 Handler: app.handler CodeUri: src/ Timeout: 10 Policies: - AWSLambdaBasicExecutionRole
Events: HelloApi: Type: Api Properties: Path: /hello Method: get
Outputs: HelloApiUrl: Description: API Gateway endpoint Value: !Sub - "https://${ApiId}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello" - ApiId: !Ref ServerlessRestApiOrganize the project as follows:
my-serverless-api/│├── template.yaml│└── src/ └── app.pyBuild and deploy the application using:
sam buildsam deploy --guidedAWS SAM creates the Lambda function, API Gateway REST API, integration, and the required Lambda invocation permission automatically.
This approach makes the infrastructure reproducible and easier to maintain across development, testing, and production environments.
Step 6: Test the API
After deployment, API Gateway provides an HTTPS endpoint.
You can test it using curl:
curl \ "https://API_ID.execute-api.REGION.amazonaws.com/Prod/hello?name=John"Expected response:
{ "message": "Hello, John!"}The request travels through API Gateway, invokes the Lambda function, and returns the generated JSON response to the client.
Security Considerations
API Gateway endpoints can be publicly accessible or protected, depending on their authorization configuration.
For production environments, consider implementing:
- Amazon Cognito: User authentication and authorization.
- IAM authorization: Restrict access to authorized AWS IAM principals.
- Lambda authorizers: Implement custom authorization logic.
- Request validation: Validate parameters and request payloads.
- Throttling: Protect the API against excessive request volumes.
- CloudWatch: Monitor Lambda execution, errors, and API performance.
It is important to remember that allowing API Gateway to invoke Lambda does not automatically authenticate API consumers. Authentication and authorization must be configured separately.
Option | Routing by method and path | Built-in auth |
|---|---|---|
API Gateway HTTP API | Yes | JWT, Lambda authorizer, IAM |
API Gateway REST API | Yes | IAM, Cognito, Lambda authorizer, API keys |
Lambda function URL | No, the function inspects method and path itself | IAM or none |
Benefits and Considerations
Using Lambda as a REST API backend offers several advantages:
- Serverless infrastructure: There are no servers to provision, patch, or maintain.
- Automatic scaling: Lambda can handle changing request volumes automatically.
- Cost efficiency: You generally pay for function invocations and execution time rather than continuously running servers.
- AWS integration: Lambda easily integrates with DynamoDB, S3, SQS, and other AWS services.
- Independent deployment: Individual functions can be updated independently.
However, there are also some considerations. Lambda functions should be designed to execute efficiently, as execution time affects cost and performance. Cold starts may introduce additional latency, particularly for infrequently invoked functions or functions with large dependencies.
It is also important to consider Lambda execution time limits, concurrency quotas, and connection management when designing applications with high traffic.
Conclusion
AWS Lambda combined with Amazon API Gateway provides an effective way to build scalable, cost-efficient REST APIs without managing traditional server infrastructure.
API Gateway handles incoming HTTP requests, while Lambda executes application logic and communicates with other AWS services. IAM resource-based policies ensure that API Gateway has permission to invoke Lambda, while Lambda execution roles control access to other AWS resources.
For smaller applications, microservices, and workloads with variable traffic, this architecture offers a flexible alternative to traditional server-based API hosting. Using AWS SAM further simplifies deployment by allowing the API, Lambda functions, and permissions to be defined and maintained as code.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article