Building a Serverless REST API on AWS - Part 2: Lambda CRUD Operations and API Gateway
Build create, read, update, and delete endpoints with Lambda, DynamoDB, validation, error handling, and API testing.
In Part 1, we designed the architecture for our serverless Task Management API and created the DynamoDB and Lambda foundations.
Now we will implement the application itself.
The final request flow will be:
Client | vAPI Gateway | vLambda | vDynamoDB
Our API will support:
POST /tasksGET /tasksGET /tasks/{taskId}PUT /tasks/{taskId}DELETE /tasks/{taskId}
Building the Lambda Handler
First, import the libraries we need:
import jsonimport osimport uuidfrom datetime import datetime, timezone
import boto3from botocore.exceptions import ClientError
Create the DynamoDB resource outside the handler:
dynamodb = boto3.resource("dynamodb")table = dynamodb.Table(os.environ["TABLE_NAME"])
Creating reusable SDK objects outside the handler allows Lambda execution environments to potentially reuse them across invocations.
Standardizing API Responses
Let's create a helper function:
def response(status_code, body): return { "statusCode": status_code, "headers": { "content-type": "application/json" }, "body": json.dumps(body) }
Now we can return:
return response(200, {"message": "Success"})
instead of repeating the complete response structure everywhere.
Creating a Task
The client sends:
POST /tasks
with:
{ "title": "Learn API Gateway", "description": "Connect API Gateway to Lambda"}
The implementation can be:
def create_task(event): try: body = json.loads(event.get("body") or "{}") except json.JSONDecodeError: return response(400, { "message": "Request body must contain valid JSON" })
title = body.get("title")
if not title or not title.strip(): return response(400, { "message": "title is required" })
task = { "taskId": str(uuid.uuid4()), "title": title.strip(), "description": body.get("description", ""), "status": "TODO", "createdAt": datetime.now(timezone.utc).isoformat() }
table.put_item(Item=task)
return response(201, task)
We generate a UUID rather than asking the client to create the primary key.
An example response is:
{ "taskId": "44ad36e8-2ff6-44aa-9ad0-a57cf136631a", "title": "Learn API Gateway", "description": "Connect API Gateway to Lambda", "status": "TODO", "createdAt": "2026-08-31T08:42:00+00:00"}
The HTTP status code is:
201 Created
Retrieving One Task
The endpoint is:
GET /tasks/{taskId}
Lambda receives the value through the API Gateway path parameters.
def get_task(task_id): result = table.get_item( Key={ "taskId": task_id } )
task = result.get("Item")
if not task: return response(404, { "message": "Task not found" })
return response(200, task)
If the item exists, DynamoDB returns it.
If no item exists with that partition key, we return:
404 Not Found
Listing Tasks
For our learning project, we can use DynamoDB
Scan :def list_tasks(): items = []
result = table.scan() items.extend(result.get("Items", []))
while "LastEvaluatedKey" in result: result = table.scan( ExclusiveStartKey=result["LastEvaluatedKey"] )
items.extend(result.get("Items", []))
return response(200, { "items": items, "count": len(items) })
Notice the pagination handling.
A DynamoDB scan may not return the entire table in a single response, so production code should not assume one
scan() call contains every record.More importantly, scanning the entire table is generally not a scalable access pattern for a large application.
A production system should usually design its DynamoDB keys and secondary indexes around specific query patterns.
For a tutorial-sized Task API, however, Scan makes the initial implementation easy to understand.
Updating a Task
We will allow these fields to change:
titledescriptionstatus
The API call is:
PUT /tasks/{taskId}
For example:
{ "status": "DONE"}
Instead of replacing the entire task, we can dynamically create a DynamoDB update expression.
def update_task(task_id, event): try: body = json.loads(event.get("body") or "{}") except json.JSONDecodeError: return response(400, { "message": "Request body must contain valid JSON" })
allowed_fields = [ "title", "description", "status" ]
updates = { key: value for key, value in body.items() if key in allowed_fields }
if not updates: return response(400, { "message": "No valid fields supplied" })
expressions = [] names = {} values = {}
for index, (field, value) in enumerate(updates.items()): name_key = f"#field{index}" value_key = f":value{index}"
expressions.append( f"{name_key} = {value_key}" )
names[name_key] = field values[value_key] = value
try: result = table.update_item( Key={ "taskId": task_id }, UpdateExpression=( "SET " + ", ".join(expressions) ), ExpressionAttributeNames=names, ExpressionAttributeValues=values, ConditionExpression="attribute_exists(taskId)", ReturnValues="ALL_NEW" )
except ClientError as error: if ( error.response["Error"]["Code"] == "ConditionalCheckFailedException" ): return response(404, { "message": "Task not found" })
raise
return response( 200, result["Attributes"] )
The important part here is:
ConditionExpression="attribute_exists(taskId)"
Without a condition, an update operation could create attributes for a key that did not previously represent an existing task.
The conditional expression protects the intended semantics of our API.
Deleting a Task
Our delete endpoint is:
DELETE /tasks/{taskId}
Implementation:
def delete_task(task_id): try: table.delete_item( Key={ "taskId": task_id }, ConditionExpression="attribute_exists(taskId)" )
except ClientError as error: if ( error.response["Error"]["Code"] == "ConditionalCheckFailedException" ): return response(404, { "message": "Task not found" })
raise
return response(200, { "message": "Task deleted" })
Again, the conditional expression allows us to distinguish between deleting an existing resource and requesting deletion of something that does not exist.
Routing Requests Inside Lambda
API Gateway provides a
routeKey .For example:
POST /tasksGET /tasksGET /tasks/{taskId}PUT /tasks/{taskId}DELETE /tasks/{taskId}
Our main handler can route requests accordingly:
def lambda_handler(event, context):
route_key = event.get("routeKey")
path_parameters = ( event.get("pathParameters") or {} )
task_id = path_parameters.get("taskId")
try:
if route_key == "POST /tasks": return create_task(event)
if route_key == "GET /tasks": return list_tasks()
if route_key == "GET /tasks/{taskId}": return get_task(task_id)
if route_key == "PUT /tasks/{taskId}": return update_task(task_id, event)
if route_key == "DELETE /tasks/{taskId}": return delete_task(task_id)
return response(404, { "message": "Route not found" })
except Exception: print("Unexpected application error")
return response(500, { "message": "Internal server error" })
For a real application, I would also use structured logging and include useful context such as the API Gateway request ID rather than relying only on simple
print() calls.
Complete Lambda Code
Putting everything together:
import jsonimport osimport uuidfrom datetime import datetime, timezone
import boto3from botocore.exceptions import ClientError
dynamodb = boto3.resource("dynamodb")table = dynamodb.Table(os.environ["TABLE_NAME"])
def response(status_code, body): return { "statusCode": status_code, "headers": { "content-type": "application/json" }, "body": json.dumps(body) }
def create_task(event): try: body = json.loads(event.get("body") or "{}") except json.JSONDecodeError: return response( 400, {"message": "Request body must contain valid JSON"} )
title = body.get("title")
if not title or not title.strip(): return response( 400, {"message": "title is required"} )
task = { "taskId": str(uuid.uuid4()), "title": title.strip(), "description": body.get("description", ""), "status": "TODO", "createdAt": datetime.now(timezone.utc).isoformat() }
table.put_item(Item=task)
return response(201, task)
def get_task(task_id): result = table.get_item( Key={"taskId": task_id} )
task = result.get("Item")
if not task: return response( 404, {"message": "Task not found"} )
return response(200, task)
def list_tasks(): items = []
result = table.scan() items.extend(result.get("Items", []))
while "LastEvaluatedKey" in result: result = table.scan( ExclusiveStartKey=result["LastEvaluatedKey"] )
items.extend(result.get("Items", []))
return response( 200, { "items": items, "count": len(items) } )
def update_task(task_id, event): try: body = json.loads(event.get("body") or "{}") except json.JSONDecodeError: return response( 400, {"message": "Request body must contain valid JSON"} )
allowed_fields = [ "title", "description", "status" ]
updates = { key: value for key, value in body.items() if key in allowed_fields }
if not updates: return response( 400, {"message": "No valid fields supplied"} )
expressions = [] names = {} values = {}
for index, (field, value) in enumerate(updates.items()): name_key = f"#field{index}" value_key = f":value{index}"
expressions.append( f"{name_key} = {value_key}" )
names[name_key] = field values[value_key] = value
try: result = table.update_item( Key={"taskId": task_id}, UpdateExpression=( "SET " + ", ".join(expressions) ), ExpressionAttributeNames=names, ExpressionAttributeValues=values, ConditionExpression="attribute_exists(taskId)", ReturnValues="ALL_NEW" )
except ClientError as error: if ( error.response["Error"]["Code"] == "ConditionalCheckFailedException" ): return response( 404, {"message": "Task not found"} )
raise
return response( 200, result["Attributes"] )
def delete_task(task_id): try: table.delete_item( Key={"taskId": task_id}, ConditionExpression="attribute_exists(taskId)" )
except ClientError as error: if ( error.response["Error"]["Code"] == "ConditionalCheckFailedException" ): return response( 404, {"message": "Task not found"} )
raise
return response( 200, {"message": "Task deleted"} )
def lambda_handler(event, context): route_key = event.get("routeKey")
path_parameters = ( event.get("pathParameters") or
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article