-
Notifications
You must be signed in to change notification settings - Fork 436
feat(event_handler): add custom response validation in OpenAPI utility #6189
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
leandrodamascena
merged 27 commits into
aws-powertools:develop
from
amin-farjadi:feature/response-validation
Mar 17, 2025
Merged
Changes from 7 commits
Commits
Show all changes
27 commits
Select commit
Hold shift + click to select a range
cc27ba7
feat(openapi-validation): Add response validation flag and distinct e…
bc69d18
feat(api-gateway-resolver): Add option for custom response validation…
6ddfdc0
feat(docs): Added doc for custom response validation error responses.
a9be196
refactor(docs): Make exception handler function name better.
276d7cd
feat(unit-test): Add tests for custom response validation error.
fb49e9b
fix: Formatting.
df105dc
fix(docs): Fix grammar in response validation docs
63fd201
fix(unit-test): fix failed CI.
1c33611
bugfix(lint): Ignore lint error FA102, irrelevant for python >=3.9
f8ead84
refactor: make response_validation_error_http_status accept more type…
eb2430b
feat(unit-test): add tests for incorrect types and invalid configs
d6b7638
Merge branch 'develop' into feature/response-validation
leandrodamascena 0090692
Merge branch 'develop' into feature/response-validation
leandrodamascena 13b7380
Merge branch 'develop' into feature/response-validation
leandrodamascena 218c666
Merge branch 'develop' into feature/response-validation
leandrodamascena 82918c7
Merge branch 'develop' into feature/response-validation
leandrodamascena 2a4d57f
refactor: rename response_validation_error_http_status to response_va…
amin-farjadi fece0e8
refactor(api_gateway): add method for validating response_validation_…
amin-farjadi f85c749
fix(api_gateway): fix type and docstring for response_validation_erro…
amin-farjadi c4f0819
fix(api_gateway): remove unncessary check of response_validation_erro…
amin-farjadi 8fe4edc
fix(openapi-validation): docstring for has_response_validation_error …
amin-farjadi f89b598
refactor(tests): move unit tests into openapi_validation functional t…
amin-farjadi f60b812
Merge branch 'develop' into feature/response-validation
leandrodamascena aaa0086
fix(tests): skipping validation for falsy response
6d5f913
Merge branch 'develop' into feature/response-validation
amin-farjadi bd93ee6
Making Ruff happy
leandrodamascena 558c03c
Refactoring documentation
leandrodamascena File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
49 changes: 49 additions & 0 deletions
49
examples/event_handler_rest/src/customizing_response_validation.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
from http import HTTPStatus | ||
from typing import Optional | ||
|
||
import requests | ||
from pydantic import BaseModel, Field | ||
|
||
from aws_lambda_powertools import Logger, Tracer | ||
from aws_lambda_powertools.event_handler import APIGatewayRestResolver, content_types | ||
from aws_lambda_powertools.event_handler.api_gateway import Response | ||
from aws_lambda_powertools.event_handler.openapi.exceptions import ResponseValidationError | ||
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, | ||
response_validation_error_http_status=HTTPStatus.INTERNAL_SERVER_ERROR, # (1)! | ||
) | ||
|
||
|
||
class Todo(BaseModel): | ||
userId: int | ||
id_: Optional[int] = Field(alias="id", default=None) | ||
title: str | ||
completed: bool | ||
|
||
@app.get("/todos_bad_response/<todo_id>") | ||
@tracer.capture_method | ||
def get_todo_by_id(todo_id: int) -> Todo: # (2)! | ||
todo = requests.get(f"https://jsonplaceholder.typicode.com/todos/{todo_id}") | ||
todo.raise_for_status() | ||
|
||
return todo.json()["title"] # (3)! | ||
|
||
@app.exception_handler(ResponseValidationError) # (4)! | ||
def handle_response_validation_error(ex: ResponseValidationError): | ||
logger.error("Request failed validation", path=app.current_event.path, errors=ex.errors()) | ||
|
||
return Response( | ||
status_code=500, | ||
content_type=content_types.APPLICATION_JSON, | ||
body="Unexpected response.", | ||
) | ||
|
||
@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) |
8 changes: 8 additions & 0 deletions
8
examples/event_handler_rest/src/response_validation_error_unsanitized_output.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
{ | ||
"statusCode": 500, | ||
"body": "{\"statusCode\": 500, \"detail\": [{\"type\": \"model_attributes_type\", \"loc\": [\"response\", ]}]}", | ||
"isBase64Encoded": false, | ||
"headers": { | ||
"Content-Type": "application/json" | ||
} | ||
} |
8 changes: 8 additions & 0 deletions
8
examples/event_handler_rest/src/response_validation_sanitized_error_output.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
{ | ||
"statusCode": 500, | ||
"body": "Unexpected response.", | ||
"isBase64Encoded": false, | ||
"headers": { | ||
"Content-Type": "application/json" | ||
} | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.