0

I'm having issues with my SQLAlchemy model schema.Particulary with this schema on my models.py:

from sqlalchemy import Boolean, Column, ForeignKey, Integer, String
from .database import Base

class User(Base):
    __tablename__ = "users"

    id = Column(Integer, primary_key=True, index=True)
    title = Column(String, index=True)
    email = Column(String, unique=True, index=True)    

and this is my main.py:

from typing import List
from fastapi import Depends, FastAPI, HTTPException,status
from sqlalchemy import schema
from sqlalchemy.orm import Session
import psycopg2
from psycopg2.extras import RealDictCursor
from . import models
from .database import SessionLocal, engine,get_db



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

app = FastAPI()



@app.get("/posts")
def get_post(db: Session=Depends(get_db)):
    posts = db.query(models.User).all()
    return{"data":posts}


@app.post("/posts", status_code=status.HTTP_201_CREATED)
def create_post(post: models.User, db: Session=Depends(get_db)):
    new_post = models.User(title=post.title, email=post.email)
    db.add(new_post)
    db.commit()
    db.refresh(new_post)

    return{"data": new_post}

The error that i get from my app main is:

fastapi.exceptions.FastAPIError: Invalid args for response field! Hint: check that <class 'app.models.User'> is a valid pydantic field type

Any ideea why is this happening? ps:i'm new to FastAPI and SQLAlchemy. Thank you in advance for your help & support.

  • 1
    Your input parameters (i.e. what you define in the view signature) should be _pydantic models_, not SQLAlchemy models. These are different libraries with different goals. `SQLModel` from the author of FastAPI might be a good middle point if you want to bridge both into a single definition. – MatsLindh Dec 15 '21 at 22:46
  • Thanks alot MatsLindh.You are right.I made the change: def create_post(post: Post , db: Session=Depends(get_db)): and now it worked. – laur2021 Dec 16 '21 at 07:32

0 Answers0