57 lines
1.9 KiB
Python
57 lines
1.9 KiB
Python
Here's the `posts.py` file with CRUD endpoints for posts:
|
|
|
|
from typing import List
|
|
from fastapi import APIRouter, Depends, HTTPException
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.db import get_db
|
|
from app.models import Post
|
|
from app.schemas import PostCreate, PostResponse
|
|
|
|
router = APIRouter()
|
|
|
|
@router.get("/posts", response_model=List[PostResponse])
|
|
def get_posts(db: Session = Depends(get_db)):
|
|
posts = db.query(Post).all()
|
|
return posts
|
|
|
|
@router.post("/posts", response_model=PostResponse)
|
|
def create_post(post: PostCreate, db: Session = Depends(get_db)):
|
|
db_post = Post(**post.dict())
|
|
db.add(db_post)
|
|
db.commit()
|
|
db.refresh(db_post)
|
|
return db_post
|
|
|
|
@router.get("/posts/{post_id}", response_model=PostResponse)
|
|
def get_post(post_id: int, db: Session = Depends(get_db)):
|
|
post = db.query(Post).filter(Post.id == post_id).first()
|
|
if not post:
|
|
raise HTTPException(status_code=404, detail="Post not found")
|
|
return post
|
|
|
|
@router.put("/posts/{post_id}", response_model=PostResponse)
|
|
def update_post(post_id: int, post: PostCreate, db: Session = Depends(get_db)):
|
|
db_post = db.query(Post).filter(Post.id == post_id).first()
|
|
if not db_post:
|
|
raise HTTPException(status_code=404, detail="Post not found")
|
|
for field, value in post.dict().items():
|
|
setattr(db_post, field, value)
|
|
db.commit()
|
|
db.refresh(db_post)
|
|
return db_post
|
|
|
|
@router.delete("/posts/{post_id}", response_model=PostResponse)
|
|
def delete_post(post_id: int, db: Session = Depends(get_db)):
|
|
post = db.query(Post).filter(Post.id == post_id).first()
|
|
if not post:
|
|
raise HTTPException(status_code=404, detail="Post not found")
|
|
db.delete(post)
|
|
db.commit()
|
|
return post
|
|
|
|
This file defines the following endpoints:
|
|
|
|
|
|
|
|
Note: Make sure to import the necessary models and schemas in the `app/models.py` and `app/schemas.py` files, respectively. |