3

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?

Daniil Fajnberg
  • 12,753
  • 2
  • 10
  • 41
Amin Ba
  • 1,603
  • 1
  • 13
  • 38
  • You may find [this answer](https://stackoverflow.com/a/73974946/17865804) helpful as well – Chris Apr 19 '23 at 05:20
  • 1
    Side note: Not sure why you need either of those to be honest. You can just `return Student(id="1", name="Alice")` directly and have the dump-and-serialize procedure done behind the scenes by FastAPI. Status code can be set in the route decorator as well. – Daniil Fajnberg Apr 19 '23 at 12:37
  • @DaniilFajnberg I want to change the status code to something custom – Amin Ba Apr 19 '23 at 13:42

1 Answers1

1

Python dict objects allow a lot of things that JSON doesn't allow. Mainly, any hashable object can be used as a dict key, and any object can be used as a dict value, without restriction.

In JSON, the keys MUST be strings written with double quotes.
Also, JSON values are limited to the types of:

  • a string
  • a number
  • an object (A JavaScript object, ~= a dict in Python)
  • an array
  • a boolean
  • null (doesn't exist in Python, but None is a close equivalent)

Jsonable_encoder will ensure that the object is valid JSON. For example, all keys will be converted to strings, Python objects in the dict values will be replaced by repr() values, etc.

nigh_anxiety
  • 1,428
  • 2
  • 4
  • 12