Closed
Description
Expected Behaviour
This may or may not be a bug, but the REST API event handler payload validator does not gracefully handle empty bodies. I would expect an empty body to raise a 4xx (maybe a 422)
Current Behaviour
With the following setup, invoking the POST /todos
endpoint with content-type: application/json
but with an empty body will raise a TypeError
and return a 500 error.
Code snippet
from typing import List, Optional
import requests
from pydantic import BaseModel, Field
from aws_lambda_powertools import Logger, Tracer
from aws_lambda_powertools.event_handler import APIGatewayRestResolver
from aws_lambda_powertools.logging import correlation_paths
from aws_lambda_powertools.utilities.typing import LambdaContext
tracer = Tracer()
logger = Logger()
app = APIGatewayRestResolver(enable_validation=True)
class Todo(BaseModel):
userId: int
id_: Optional[int] = Field(alias="id", default=None)
title: str
completed: bool
@app.post("/todos")
def create_todo(todo: Todo) -> str:
response = requests.post("https://jsonplaceholder.typicode.com/todos", json=todo.dict(by_alias=True))
response.raise_for_status()
return response.json()["id"]
@logger.inject_lambda_context(correlation_id_path=correlation_paths.API_GATEWAY_HTTP)
@tracer.capture_lambda_handler
def lambda_handler(event: dict, context: LambdaContext) -> dict:
return app.resolve(event, context)
Possible Solution
The validation middleware handles a json.JSONDecodeError
exception, but json.loads
will raise a TypeError
if the request body is empty.
We could either:
- Catch the
TypeError
and raise an appropriate response - Check for
None
in_get_body
Steps to Reproduce
Invoke the REST endpoint with an empty body.
Powertools for AWS Lambda (Python) version
latest
AWS Lambda function runtime
3.12
Packaging format used
PyPi
Debugging logs
No response
Metadata
Metadata
Assignees
Labels
Type
Projects
Status
Shipped