
This commit includes: - Basic project structure with FastAPI - SQLite database integration using SQLAlchemy - CRUD API for items - Alembic migrations setup - Health check endpoint - Proper error handling - Updated README with setup instructions
92 lines
2.2 KiB
Python
92 lines
2.2 KiB
Python
from typing import List
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException, status
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.db.session import get_db
|
|
from app.models.item import Item as ItemModel
|
|
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,
|
|
db: Session = Depends(get_db)
|
|
):
|
|
"""
|
|
Retrieve items.
|
|
"""
|
|
items = db.query(ItemModel).offset(skip).limit(limit).all()
|
|
return items
|
|
|
|
|
|
@router.post("/", response_model=Item, status_code=status.HTTP_201_CREATED)
|
|
def create_item(
|
|
item_in: ItemCreate,
|
|
db: Session = Depends(get_db)
|
|
):
|
|
"""
|
|
Create new item.
|
|
"""
|
|
db_item = ItemModel(**item_in.model_dump())
|
|
db.add(db_item)
|
|
db.commit()
|
|
db.refresh(db_item)
|
|
return db_item
|
|
|
|
|
|
@router.get("/{item_id}", response_model=Item)
|
|
def read_item(
|
|
item_id: int,
|
|
db: Session = Depends(get_db)
|
|
):
|
|
"""
|
|
Get item by ID.
|
|
"""
|
|
db_item = db.query(ItemModel).filter(ItemModel.id == item_id).first()
|
|
if db_item is None:
|
|
raise HTTPException(status_code=404, detail="Item not found")
|
|
return db_item
|
|
|
|
|
|
@router.put("/{item_id}", response_model=Item)
|
|
def update_item(
|
|
item_id: int,
|
|
item_in: ItemUpdate,
|
|
db: Session = Depends(get_db)
|
|
):
|
|
"""
|
|
Update an item.
|
|
"""
|
|
db_item = db.query(ItemModel).filter(ItemModel.id == item_id).first()
|
|
if db_item is None:
|
|
raise HTTPException(status_code=404, detail="Item not found")
|
|
|
|
update_data = item_in.model_dump(exclude_unset=True)
|
|
for field, value in update_data.items():
|
|
setattr(db_item, field, value)
|
|
|
|
db.add(db_item)
|
|
db.commit()
|
|
db.refresh(db_item)
|
|
return db_item
|
|
|
|
|
|
@router.delete("/{item_id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None)
|
|
def delete_item(
|
|
item_id: int,
|
|
db: Session = Depends(get_db)
|
|
):
|
|
"""
|
|
Delete an item.
|
|
"""
|
|
db_item = db.query(ItemModel).filter(ItemModel.id == item_id).first()
|
|
if db_item is None:
|
|
raise HTTPException(status_code=404, detail="Item not found")
|
|
|
|
db.delete(db_item)
|
|
db.commit()
|
|
return None |