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?)?
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
dictand 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) # -> dictto 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
Responseand 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.