Search code examples
pythonfastapi

TypeError: Object of type Project is not JSON serializable


I am learning FastAPI.

My code:

main.py

from . import models, schemas
from .database import SessionLocal, engine

models.Base.metadata.create_all(bind=engine)

app = FastAPI()

# Dependency
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

@app.get("/projects/", response_model=list[schemas.ProjectSchema])
def list_project(db: Session = Depends(get_db)):
    """ Get all projects"""
    projects = db.query(models.Project).all()
    print("XXX_ ", projects) # XXX_  [<src.models.Project ...]
    return JSONResponse(content={"message": projects})

models.py

from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import relationship
from .database import Base

class Project(Base):
    __tablename__ = "projects"
    id = Column(Integer, primary_key=True)
    name = Column(String, nullable=False, unique=True)

schemas.py

from typing import List, Union
from pydantic import BaseModel

class ProjectSchema(BaseModel):
    name: str
    class Config:
        orm_mode = True

I have an error for GET /projects request:

TypeError: Object of type Project is not JSON serializable

I have read FastAPI TypeError: Object of type 'ModelMetaclass' is not JSON serializable.

I checked that response_model=list[schemas.ProjectSchema] is OK. How to fix the error?


Solution

  • You're trying to return the JSON data to a Object response and more over you're trying to feed Object to JSON.

    You can try return projects this will work.