Middleware return object #7964
Unanswered
Nils-Mohr-BA
asked this question in
Q&A
Replies: 1 comment
-
|
Hey! Thanks for raising this question. I may not have fully understood your question and I'm wondering if you could you share a quick code snippet of what you're trying to achieve? If you want your handler to return a custom object and convert it to from aws_lambda_powertools.event_handler import APIGatewayRestResolver, Response
from dataclasses import dataclass
app = APIGatewayRestResolver()
@dataclass
class MyCustomResponse:
data: dict
status: int = 200
def response_converter_middleware(app, next_middleware):
result = next_middleware(app)
# Already a Response, return as-is
if isinstance(result, Response):
return result
# Convert custom response to Powertools Response
if isinstance(result, MyCustomResponse):
return Response(
status_code=result.status,
content_type="application/json",
body=result.data,
)
# Fallback
return Response(status_code=200, body=result)
app.use([response_converter_middleware])
@app.get("/hello")
def hello():
# Return your custom object - middleware converts it
return MyCustomResponse(data={"message": "Hello!"}, status=200)The middleware wraps |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Hi,
we have started implementing our own middleware, but we are wondering if there is any way to change the object we get back.
At the moment we always get the Response back, but ideally we would like to return our own custom response and we would handle the conversion to the powertools Response in our middleware.
Is there any way to make this work?
Thanks
Beta Was this translation helpful? Give feedback.
All reactions