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?)?