Automated Action 7fdb11e728 Create FastAPI REST API with SQLite database and CRUD operations
- Set up project structure with FastAPI, SQLAlchemy, and Alembic
- Create database models for User and Item
- Implement CRUD operations for all models
- Create API endpoints with validation
- Add health check endpoint
- Configure CORS middleware
- Set up database migrations
- Add comprehensive documentation in README
2025-05-21 08:51:23 +00:00

112 lines
2.6 KiB
Python

from typing import Any, List
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app import schemas
from app.api import deps
from app.crud.crud_item import item
from app.crud.crud_user import user
router = APIRouter()
@router.get("/", response_model=List[schemas.Item])
def read_items(
db: Session = Depends(deps.get_db),
skip: int = 0,
limit: int = 100,
) -> Any:
"""
Retrieve items.
"""
items = item.get_multi(db, skip=skip, limit=limit)
return items
@router.post("/", response_model=schemas.Item)
def create_item(
*,
db: Session = Depends(deps.get_db),
item_in: schemas.ItemCreate,
owner_id: int,
) -> Any:
"""
Create new item.
"""
owner = user.get(db, id=owner_id)
if not owner:
raise HTTPException(
status_code=404,
detail="Owner not found",
)
item_obj = item.create_with_owner(db=db, obj_in=item_in, owner_id=owner_id)
return item_obj
@router.get("/{id}", response_model=schemas.Item)
def read_item(
*,
db: Session = Depends(deps.get_db),
id: int,
) -> Any:
"""
Get item by ID.
"""
item_obj = item.get(db=db, id=id)
if not item_obj:
raise HTTPException(status_code=404, detail="Item not found")
return item_obj
@router.put("/{id}", response_model=schemas.Item)
def update_item(
*,
db: Session = Depends(deps.get_db),
id: int,
item_in: schemas.ItemUpdate,
) -> Any:
"""
Update an item.
"""
item_obj = item.get(db=db, id=id)
if not item_obj:
raise HTTPException(status_code=404, detail="Item not found")
item_obj = item.update(db=db, db_obj=item_obj, obj_in=item_in)
return item_obj
@router.delete("/{id}", response_model=schemas.Item)
def delete_item(
*,
db: Session = Depends(deps.get_db),
id: int,
) -> Any:
"""
Delete an item.
"""
item_obj = item.get(db=db, id=id)
if not item_obj:
raise HTTPException(status_code=404, detail="Item not found")
item_obj = item.remove(db=db, id=id)
return item_obj
@router.get("/user/{owner_id}", response_model=List[schemas.Item])
def read_items_by_owner(
owner_id: int,
db: Session = Depends(deps.get_db),
skip: int = 0,
limit: int = 100,
) -> Any:
"""
Retrieve items by owner.
"""
owner = user.get(db, id=owner_id)
if not owner:
raise HTTPException(
status_code=404,
detail="Owner not found",
)
items = item.get_multi_by_owner(db=db, owner_id=owner_id, skip=skip, limit=limit)
return items