
- Set up project structure with FastAPI framework - Implement database models using SQLAlchemy - Create Alembic migrations for database schema - Build CRUD endpoints for Items resource - Add health check endpoint - Include API documentation with Swagger and ReDoc - Update README with project documentation
93 lines
2.2 KiB
Python
93 lines
2.2 KiB
Python
from typing import List, Optional
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException, status
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.crud import get_item, get_items, create_item, update_item, delete_item
|
|
from app.db.database import get_db
|
|
from app.schemas.item import Item, ItemCreate, ItemUpdate
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
@router.get("/", response_model=List[Item])
|
|
def read_items(
|
|
skip: int = 0,
|
|
limit: int = 100,
|
|
name: Optional[str] = None,
|
|
is_active: Optional[bool] = None,
|
|
db: Session = Depends(get_db)
|
|
):
|
|
"""
|
|
Retrieve items with optional filtering.
|
|
"""
|
|
filters = {}
|
|
if name is not None:
|
|
filters["name"] = name
|
|
if is_active is not None:
|
|
filters["is_active"] = is_active
|
|
|
|
return get_items(db, skip=skip, limit=limit, filter_dict=filters)
|
|
|
|
|
|
@router.post("/", response_model=Item, status_code=status.HTTP_201_CREATED)
|
|
def create_new_item(
|
|
item: ItemCreate,
|
|
db: Session = Depends(get_db)
|
|
):
|
|
"""
|
|
Create a new item.
|
|
"""
|
|
return create_item(db=db, item=item)
|
|
|
|
|
|
@router.get("/{item_id}", response_model=Item)
|
|
def read_item(
|
|
item_id: int,
|
|
db: Session = Depends(get_db)
|
|
):
|
|
"""
|
|
Get a specific item by ID.
|
|
"""
|
|
db_item = get_item(db=db, item_id=item_id)
|
|
if db_item is None:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail="Item not found"
|
|
)
|
|
return db_item
|
|
|
|
|
|
@router.put("/{item_id}", response_model=Item)
|
|
def update_existing_item(
|
|
item_id: int,
|
|
item: ItemUpdate,
|
|
db: Session = Depends(get_db)
|
|
):
|
|
"""
|
|
Update an item.
|
|
"""
|
|
db_item = update_item(db=db, item_id=item_id, item=item)
|
|
if db_item is None:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail="Item not found"
|
|
)
|
|
return db_item
|
|
|
|
|
|
@router.delete("/{item_id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None)
|
|
def delete_existing_item(
|
|
item_id: int,
|
|
db: Session = Depends(get_db)
|
|
):
|
|
"""
|
|
Delete an item.
|
|
"""
|
|
success = delete_item(db=db, item_id=item_id)
|
|
if not success:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail="Item not found"
|
|
)
|
|
return None |