I have this Pydantic model:
from pydantic import BaseModel
class Student(BaseModel):
name: str
id: str
I see in the FastAPI docs that if we want to pass it the JSONResponse
, we do it like this:
from fastapi import FastAPI
from fastapi.encoders import jsonable_encoder
from fastapi.responses import JSONResponse
app = FastAPI()
@app.get("/")
def get_a_specific_student():
s = Student(id="1", name="Alice")
status_code = 200
content = jsonable_encoder(s)
return JSONResponse(status_code=status_code, content=content)
We could instead do:
@app.get("/")
def get_a_specific_student():
s = Student(id="1", name="Alice")
status_code = 200
content = s.dict()
return JSONResponse(status_code=status_code, content=content)
What is the difference between calling the dict
method of a Pydantic object and passing it to jsonable_encoder
?