|
| 1 | +import secrets |
| 2 | + |
| 3 | +import uvicorn |
| 4 | +from fastapi import Depends, FastAPI, HTTPException |
| 5 | +from pydantic import BaseModel |
| 6 | +from sqlalchemy import Integer, String, create_engine |
| 7 | +from sqlalchemy.orm import ( |
| 8 | + DeclarativeBase, |
| 9 | + Mapped, |
| 10 | + Session, |
| 11 | + mapped_column, |
| 12 | + sessionmaker, |
| 13 | +) |
| 14 | + |
| 15 | +# --- Database setup --- |
| 16 | + |
| 17 | +DATABASE_URL = "sqlite:///./books.db" |
| 18 | +engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False}) |
| 19 | + |
| 20 | +SessionLocal = sessionmaker(bind=engine, autoflush=False) |
| 21 | + |
| 22 | + |
| 23 | +# declarative base class |
| 24 | +class Base(DeclarativeBase): |
| 25 | + pass |
| 26 | + |
| 27 | + |
| 28 | +# --- SQLAlchemy ORM model --- |
| 29 | + |
| 30 | + |
| 31 | +class Book(Base): |
| 32 | + __tablename__ = "books" |
| 33 | + |
| 34 | + id: Mapped[str] = mapped_column( |
| 35 | + primary_key=True, default=lambda: secrets.token_hex(12) |
| 36 | + ) |
| 37 | + title: Mapped[str] = mapped_column(String, nullable=False) |
| 38 | + author: Mapped[str] = mapped_column(String, nullable=False) |
| 39 | + pages: Mapped[int] = mapped_column(Integer, default=0) |
| 40 | + |
| 41 | + |
| 42 | +# --- Pydantic models --- |
| 43 | + |
| 44 | + |
| 45 | +class BookCreate(BaseModel): |
| 46 | + title: str |
| 47 | + author: str |
| 48 | + pages: int = 0 |
| 49 | + |
| 50 | + |
| 51 | +class BookResponse(BaseModel): |
| 52 | + id: str |
| 53 | + title: str |
| 54 | + author: str |
| 55 | + pages: int |
| 56 | + |
| 57 | + class Config: |
| 58 | + from_attributes = True # allows conversion from ORM objects |
| 59 | + |
| 60 | + |
| 61 | +# --- Dependency to get a DB session --- |
| 62 | + |
| 63 | + |
| 64 | +def get_db(): |
| 65 | + db = SessionLocal() |
| 66 | + try: |
| 67 | + yield db |
| 68 | + finally: |
| 69 | + db.close() |
| 70 | + |
| 71 | + |
| 72 | +# --- FastAPI setup --- |
| 73 | + |
| 74 | +app = FastAPI() |
| 75 | + |
| 76 | +# Create tables |
| 77 | +Base.metadata.create_all(bind=engine) |
| 78 | + |
| 79 | +# --- Routes --- |
| 80 | + |
| 81 | + |
| 82 | +@app.post("/books/", response_model=BookResponse) |
| 83 | +def create_book(book_data: BookCreate, db: Session = Depends(get_db)): |
| 84 | + book = Book(**book_data.model_dump()) |
| 85 | + db.add(book) |
| 86 | + db.commit() |
| 87 | + db.refresh(book) |
| 88 | + return book |
| 89 | + |
| 90 | + |
| 91 | +@app.get("/books/{book_id}", response_model=BookResponse) |
| 92 | +def get_book(book_id: str, db: Session = Depends(get_db)): |
| 93 | + book = db.get(Book, book_id) |
| 94 | + if not book: |
| 95 | + raise HTTPException(status_code=404, detail="Book not found") |
| 96 | + return book |
| 97 | + |
| 98 | + |
| 99 | +@app.get("/books/", response_model=list[BookResponse]) |
| 100 | +def list_books(db: Session = Depends(get_db)): |
| 101 | + return db.query(Book).all() |
| 102 | + |
| 103 | + |
| 104 | +if __name__ == "__main__": |
| 105 | + uvicorn.run(app, host="0.0.0.0", port=8000) |
0 commit comments