how to create a post request using fast api and sqlalchemy while working with a foreign key constraint

Viewed 548

This is my first time using FastApi the python framework and i am trying to understand how to correctly setup my tables and logic to be able to make a post request that create an instance of the table that has the foreign key

models.py

class User(Base):
    __tablename__ = "users"
    id = Column(Integer, primary_key=True, index=True)
    first_name = Column(Text, nullable=False)
    last_name = Column(Text, nullable=False)

class Post(Base):
    __tablename__ = "posts"
    id = Column(Integer, primary_key=True, index=True)
    user_id = Column(Integer, ForeignKey("users.id"), nullable=False)

schemas.py

class UserBase(BaseModel):
    name: str

class Posts(BaseModel):
    id: int
    user_id: int

    class Config:
        orm_mode = True

class User(UserBase):
    id: int

    class Config:
        orm_mode = True

repository.py

def create_post(db: Session, user_id: int, post: schemas.Post):
    get_user_id = db.query(models.User).filter(models.User.id == user_id).first()
    
    post = models.Post(
        id=post.id,
        user_id=get_user_id.id,
    )

    db.add(post)
    db.commit()
    db.refresh(post)
    return post

endpoint

router = APIRouter()

@router.post("/posts.", response_model=Post)
async def create_post(user_id, post: Post, db):
    return repository.create_post(db=db, user_id=user_id, post=post)

front end

try {
       const url = "http://localhost:8000/posts";
       const data = {"user_id": 2};


       const response = await fetch(url, {
           method: "POST",
           headers: {
                        "Content-Type": "application/json",
                    },
                    body: JSON.stringify(data)
                })
...

The user_id tried above in the front end exist in the database and the endpoint to create a user work fine but just the one to create a post that belong to a specific user do not work return a 422 (Unprocessable Entity)

Is there something that i am doing wrong?

1 Answers

Your endpoint currently requires 2 things: a user_id and data from a Post schema. (It also asks for db which I don't know how you manage your access to your db) (create_post(user_id, post: Post, db))

So your body must contain the values of Post, namely: id and user_id. At this point, we realize that you ask twice in your endpoint user_id . You can therefore delete your first user_id from your endpoint since it is included in your Post schema.

On the front-end, your data contains only one data: {"user_id": 2}. It is missing the value for id which is requested via your Post schema. So, since there is one piece of data missing, a 422 error is raised.

Related