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?