
- Add FastAPI application with CORS support - Implement SQLite database with SQLAlchemy - Create Item model with CRUD operations - Setup Alembic for database migrations - Add comprehensive API endpoints for Items - Include health check endpoint - Update README with documentation
67 lines
2.1 KiB
Python
67 lines
2.1 KiB
Python
from fastapi import FastAPI, Depends, HTTPException
|
|
from fastapi.middleware.cors import CORSMiddleware
|
|
from sqlalchemy.orm import Session
|
|
from typing import List
|
|
|
|
from app.db.session import get_db, engine
|
|
from app.db.base import Base
|
|
from app import crud, schemas
|
|
|
|
app = FastAPI(
|
|
title="REST API Service",
|
|
description="A REST API service built with FastAPI",
|
|
version="1.0.0",
|
|
openapi_url="/openapi.json"
|
|
)
|
|
|
|
app.add_middleware(
|
|
CORSMiddleware,
|
|
allow_origins=["*"],
|
|
allow_credentials=True,
|
|
allow_methods=["*"],
|
|
allow_headers=["*"],
|
|
)
|
|
|
|
Base.metadata.create_all(bind=engine)
|
|
|
|
@app.get("/")
|
|
async def root():
|
|
return {
|
|
"title": "REST API Service",
|
|
"documentation": "/docs",
|
|
"health_check": "/health"
|
|
}
|
|
|
|
@app.get("/health")
|
|
async def health_check():
|
|
return {"status": "healthy", "service": "REST API Service"}
|
|
|
|
@app.post("/items/", response_model=schemas.Item)
|
|
def create_item(item: schemas.ItemCreate, db: Session = Depends(get_db)):
|
|
return crud.create_item(db=db, item=item)
|
|
|
|
@app.get("/items/", response_model=List[schemas.Item])
|
|
def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
|
|
items = crud.get_items(db, skip=skip, limit=limit)
|
|
return items
|
|
|
|
@app.get("/items/{item_id}", response_model=schemas.Item)
|
|
def read_item(item_id: int, db: Session = Depends(get_db)):
|
|
db_item = crud.get_item(db, item_id=item_id)
|
|
if db_item is None:
|
|
raise HTTPException(status_code=404, detail="Item not found")
|
|
return db_item
|
|
|
|
@app.put("/items/{item_id}", response_model=schemas.Item)
|
|
def update_item(item_id: int, item: schemas.ItemUpdate, db: Session = Depends(get_db)):
|
|
db_item = crud.update_item(db, item_id=item_id, item=item)
|
|
if db_item is None:
|
|
raise HTTPException(status_code=404, detail="Item not found")
|
|
return db_item
|
|
|
|
@app.delete("/items/{item_id}")
|
|
def delete_item(item_id: int, db: Session = Depends(get_db)):
|
|
db_item = crud.delete_item(db, item_id=item_id)
|
|
if db_item is None:
|
|
raise HTTPException(status_code=404, detail="Item not found")
|
|
return {"message": "Item deleted successfully"} |