Return a Response Directly¶
When you create aFastAPIpath operation you can normally return any data from it: adict, alist, a Pydantic model, a database model, etc.
By default,FastAPI would automatically convert that return value to JSON using thejsonable_encoder explained inJSON Compatible Encoder.
Then, behind the scenes, it would put that JSON-compatible data (e.g. adict) inside of aJSONResponse that would be used to send the response to the client.
But you can return aJSONResponse directly from yourpath operations.
It might be useful, for example, to return custom headers or cookies.
Return aResponse¶
In fact, you can return anyResponse or any sub-class of it.
Tip
JSONResponse itself is a sub-class ofResponse.
And when you return aResponse,FastAPI will pass it directly.
It won't do any data conversion with Pydantic models, it won't convert the contents to any type, etc.
This gives you a lot of flexibility. You can return any data type, override any data declaration or validation, etc.
Using thejsonable_encoder in aResponse¶
BecauseFastAPI doesn't make any changes to aResponse you return, you have to make sure its contents are ready for it.
For example, you cannot put a Pydantic model in aJSONResponse without first converting it to adict with all the data types (likedatetime,UUID, etc) converted to JSON-compatible types.
For those cases, you can use thejsonable_encoder to convert your data before passing it to a response:
fromdatetimeimportdatetimefromfastapiimportFastAPIfromfastapi.encodersimportjsonable_encoderfromfastapi.responsesimportJSONResponsefrompydanticimportBaseModelclassItem(BaseModel):title:strtimestamp:datetimedescription:str|None=Noneapp=FastAPI()@app.put("/items/{id}")defupdate_item(id:str,item:Item):json_compatible_item_data=jsonable_encoder(item)returnJSONResponse(content=json_compatible_item_data)Technical Details
You could also usefrom starlette.responses import JSONResponse.
FastAPI provides the samestarlette.responses asfastapi.responses just as a convenience for you, the developer. But most of the available responses come directly from Starlette.
Returning a customResponse¶
The example above shows all the parts you need, but it's not very useful yet, as you could have just returned theitem directly, andFastAPI would put it in aJSONResponse for you, converting it to adict, etc. All that by default.
Now, let's see how you could use that to return a custom response.
Let's say that you want to return anXML response.
You could put your XML content in a string, put that in aResponse, and return it:
fromfastapiimportFastAPI,Responseapp=FastAPI()@app.get("/legacy/")defget_legacy_data():data="""<?xml version="1.0"?> <shampoo> <Header> Apply shampoo here. </Header> <Body> You'll have to use soap here. </Body> </shampoo> """returnResponse(content=data,media_type="application/xml")Notes¶
When you return aResponse directly its data is not validated, converted (serialized), or documented automatically.
But you can still document it as described inAdditional Responses in OpenAPI.
You can see in later sections how to use/declare these customResponses while still having automatic data conversion, documentation, etc.







