58 lines
2.2 KiB
Python
58 lines
2.2 KiB
Python
from typing import List
|
|
from fastapi import APIRouter, Depends, HTTPException, status
|
|
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.post("/posts", response_model=PostResponse, status_code=status.HTTP_201_CREATED)
|
|
def create_post(post: PostCreate, db: Session = Depends(get_db)):
|
|
new_post = Post(**post.dict())
|
|
db.add(new_post)
|
|
db.commit()
|
|
db.refresh(new_post)
|
|
return new_post
|
|
|
|
@router.get("/posts", response_model=List[PostResponse])
|
|
def get_all_posts(db: Session = Depends(get_db)):
|
|
posts = db.query(Post).all()
|
|
return posts
|
|
|
|
@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=status.HTTP_404_NOT_FOUND, 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=status.HTTP_404_NOT_FOUND, detail="Post not found")
|
|
update_data = post.dict(exclude_unset=True)
|
|
for key, value in update_data.items():
|
|
setattr(db_post, key, value)
|
|
db.commit()
|
|
db.refresh(db_post)
|
|
return db_post
|
|
|
|
@router.delete("/posts/{post_id}", status_code=status.HTTP_204_NO_CONTENT)
|
|
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=status.HTTP_404_NOT_FOUND, detail="Post not found")
|
|
db.delete(post)
|
|
db.commit()
|
|
return
|
|
|
|
This file defines the following endpoints:
|
|
|
|
|
|
The endpoints use SQLAlchemy models (`Post`) and Pydantic schemas (`PostCreate`, `PostResponse`) for data validation and serialization. The `get_db` dependency function from `app.db` is used to get a database session.
|
|
|
|
|
|
Note: You'll need to define the `Post` model in `app/models.py` and the `PostCreate` and `PostResponse` schemas in `app/schemas.py` for this code to work properly. |