44 lines
2.1 KiB
Python
44 lines
2.1 KiB
Python
# app/api/v1/routes/posts.py
|
|
|
|
from typing import List
|
|
from fastapi import APIRouter, Depends, HTTPException
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.api.v1.models.posts import Posts
|
|
from app.api.v1.schemas.posts import PostsCreate, PostsResponse
|
|
from app.api.core.dependencies.dependencies import get_db
|
|
|
|
router = APIRouter()
|
|
|
|
@router.get("/postss", response_model=List[PostsResponse])
|
|
def get_postss(db: Session = Depends(get_db)):
|
|
postss = db.query(Posts).all()
|
|
return postss
|
|
|
|
@router.post("/postss", response_model=PostsResponse)
|
|
def create_posts(posts: PostsCreate, db: Session = Depends(get_db)):
|
|
db_posts = Posts(**posts.dict())
|
|
db.add(db_posts)
|
|
db.commit()
|
|
db.refresh(db_posts)
|
|
return db_posts
|
|
|
|
@router.get("/postss/{id}", response_model=PostsResponse)
|
|
def get_posts(id: int, db: Session = Depends(get_db)):
|
|
db_posts = db.query(Posts).filter(Posts.id == id).first()
|
|
if not db_posts:
|
|
raise HTTPException(status_code=404, detail="Posts not found")
|
|
return db_posts
|
|
```
|
|
|
|
This code defines a FastAPI router with three endpoints:
|
|
|
|
1. `GET /postss`: Lists all posts from the database. It uses the `Posts` model from `app.api.v1.models.posts` and returns a list of `PostsResponse` schemas from `app.api.v1.schemas.posts`.
|
|
|
|
2. `POST /postss`: Creates a new post in the database. It accepts a `PostsCreate` schema from `app.api.v1.schemas.posts` as the request body, creates a new `Posts` model instance, adds it to the database, and returns the created `PostsResponse` schema.
|
|
|
|
3. `GET /postss/{id}`: Retrieves a specific post by ID from the database. It uses the `Posts` model from `app.api.v1.models.posts` and returns a `PostsResponse` schema from `app.api.v1.schemas.posts`. If the post with the given ID is not found, it raises an `HTTPException` with a 404 status code.
|
|
|
|
All the endpoints use the `get_db` dependency from `app.api.core.dependencies.dependencies` to obtain a database session.
|
|
|
|
Note: This code assumes that the `Posts` model, `PostsCreate` schema, and `PostsResponse` schema exist in the specified locations. You may need to create or modify these files based on your project's requirements. |