Managing API responses
The use of jsonable_encoder()
can help an API method not only with data persistency problems but also with the integrity and correctness of its response. In the signup()
service method, JSONResponse
returns the encoded Tourist
model instead of the original object to ensure that the client always received a JSON response. Aside from raising status codes and providing error messages, JSONResponse
can also do some tricks in handling the API responses to the client. Although optional in many circumstances, applying the encoder method when generating responses is recommended to avoid runtime errors:
from fastapi.encoders import jsonable_encoder from fastapi.responses import JSONResponse @router.get("/ch02/destinations/details/{id}") def check_tour_profile(id: UUID): tour_info_json = jsonable_encoder(tours[id]) return JSONResponse(content=tour_info_json)
check_tour_profile()
here uses JSONResponse
to ensure...