I am exploring FastAPI, and got it working on my Docker Desktop on Windows. Here’s my main.py
which is deployed successfully in Docker:
#main.py
import fastapi
import json
from fastapi.responses import JSONResponse
app = fastapi.FastAPI()
@app.get('/api/get_weights1')
async def get_weights1():
weights = {'aa': 10, 'bb': 20}
return json.dumps(weights)
@app.get('/api/get_weights2')
async def get_weights2():
weights = {'aa': 10, 'bb': 20}
return JSONResponse(content=weights, status_code=200)
And I have a simple python file get_weights.py
to make requests to those 2 APIs:
#get_weights.py
import requests
import json
resp = requests.get('http://127.0.0.1:8000/api/get_weights1')
print('ok', resp.status_code)
if resp.status_code == 200:
print(resp.json())
resp = requests.get('http://127.0.0.1:8000/api/get_weights2')
print('ok', resp.status_code)
if resp.status_code == 200:
print(resp.json())
I get the same responses from the 2 APIs, output:
ok 200
{"aa": 10, "bb": 20}
ok 200
{'aa': 10, 'bb': 20}
The response seems the same whether I use json.dumps()
or JSONResponse()
. I’ve read the FastAPI documentation on JSONResponse, but I still have below questions:
May I know if there is any difference between the 2 methods?
If there is a difference, which method is recommended (and why?)?
2
Answers
I've experimented a few variations and found the following...
(1) Both methods are not able to serialize a datetime object. For example if the weights are:
then both methods will have the same returned status and error:
To overcome this use
and
(2) I've also experimented returning the plain
dict
as it is, especially if there is a datetime object in it. As @Matija has mentioned, FastAPI will automatically stringify thisdict
and wrap it in the response. For example:Output:
(3) As @Matija has mentioned,
JSONResponse()
method allows customization of the returned response. For example, the response status could be customized as 201 (instead of 200). And also different types of objects to be returned. This is probably the advantage of using this method overjson.dumps()
method. For example:Same output as before:
In FastAPI you can create response 3 different ways (from most concise to most flexible):
1
In docs you linked we can see that FastAPI will automatically stringify this
dict
and wrap it inJSONResponse
. This way is most concise and covers majority of use cases.2
However sometimes you have to return custom headers (for example
REMOTE-USER=username
) or different status code (maybe 201 – Created or 202 – Accepted). This case you need to useJSONResponse
.Problem is that now if we don’t have simple dict, we have to use
jsonable_encoder(some_model) # -> dict
to get it. So it’s a tad more verbose. For available options check Starlette documentation, since FastAPI just reexports it.More complex example:
3
Finally you do not need to return json – you can also return csv, html or any other type of file. This case we have to use
Response
and specifymedia_type
. Likewise use Starlette docs.In short
Note that Fastapi documentation states:
So we see what is difference: first method has good integration with other FastAPI functionality, so should always be preferred. Use second option only if you need to provide custom headers or status codes. Finally, use third option only if you want to return something that is not json.