Automated Action 02cc12cad8 Add FastAPI REST API service with CRUD operations
- Created main FastAPI application with CORS middleware
- Added SQLite database configuration with SQLAlchemy
- Implemented Items model with create, read, update, delete operations
- Set up Alembic migrations for database schema management
- Added comprehensive API endpoints at /api/v1/items/
- Included health check endpoint at /health
- Added proper Pydantic schemas for request/response validation
- Updated README with complete documentation and usage instructions
- Configured Ruff for code linting and formatting
2025-06-20 10:55:10 +00:00

58 lines
1.8 KiB
Python

from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import List
from app.db.session import get_db
from app.models.item import Item
from app.schemas.item import Item as ItemSchema, ItemCreate, ItemUpdate
router = APIRouter()
@router.post("/items/", response_model=ItemSchema, status_code=status.HTTP_201_CREATED)
def create_item(item: ItemCreate, db: Session = Depends(get_db)):
db_item = Item(**item.dict())
db.add(db_item)
db.commit()
db.refresh(db_item)
return db_item
@router.get("/items/", response_model=List[ItemSchema])
def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
items = db.query(Item).offset(skip).limit(limit).all()
return items
@router.get("/items/{item_id}", response_model=ItemSchema)
def read_item(item_id: int, db: Session = Depends(get_db)):
item = db.query(Item).filter(Item.id == item_id).first()
if item is None:
raise HTTPException(status_code=404, detail="Item not found")
return item
@router.put("/items/{item_id}", response_model=ItemSchema)
def update_item(item_id: int, item_update: ItemUpdate, db: Session = Depends(get_db)):
item = db.query(Item).filter(Item.id == item_id).first()
if item is None:
raise HTTPException(status_code=404, detail="Item not found")
update_data = item_update.dict(exclude_unset=True)
for field, value in update_data.items():
setattr(item, field, value)
db.commit()
db.refresh(item)
return item
@router.delete("/items/{item_id}")
def delete_item(item_id: int, db: Session = Depends(get_db)):
item = db.query(Item).filter(Item.id == item_id).first()
if item is None:
raise HTTPException(status_code=404, detail="Item not found")
db.delete(item)
db.commit()
return {"message": "Item deleted successfully"}