|
| 1 | +from fastapi import FastAPI, HTTPException, Depends |
| 2 | +from sqlalchemy import select |
| 3 | +from sqlalchemy.orm import Session |
| 4 | +from pydantic import BaseModel, ConfigDict |
| 5 | + |
| 6 | +from crud_sql_alchemy import Bird, init_db |
| 7 | +from crud_sql_alchemy import Session as SessionLocal |
| 8 | + |
| 9 | +app = FastAPI() |
| 10 | +init_db() |
| 11 | + |
| 12 | + |
| 13 | +class BirdCreate(BaseModel): |
| 14 | + name: str |
| 15 | + |
| 16 | + |
| 17 | +class BirdUpdate(BaseModel): |
| 18 | + name: str |
| 19 | + |
| 20 | + |
| 21 | +class BirdResponse(BaseModel): |
| 22 | + model_config = ConfigDict(from_attributes=True) |
| 23 | + |
| 24 | + id: int |
| 25 | + name: str |
| 26 | + |
| 27 | + |
| 28 | +def get_db(): |
| 29 | + db = SessionLocal() |
| 30 | + try: |
| 31 | + yield db |
| 32 | + finally: |
| 33 | + db.close() |
| 34 | + |
| 35 | + |
| 36 | +@app.post("/birds/", response_model=BirdResponse) |
| 37 | +def create_bird(bird: BirdCreate, db: Session = Depends(get_db)): |
| 38 | + new_bird = Bird(name=bird.name) |
| 39 | + db.add(new_bird) |
| 40 | + db.commit() |
| 41 | + db.refresh(new_bird) |
| 42 | + return new_bird |
| 43 | + |
| 44 | + |
| 45 | +@app.get("/birds/", response_model=list[BirdResponse]) |
| 46 | +def read_birds(db: Session = Depends(get_db)): |
| 47 | + birds = db.execute(select(Bird)).scalars().all() |
| 48 | + return birds |
| 49 | + |
| 50 | + |
| 51 | +@app.get("/birds/{bird_id}", response_model=BirdResponse) |
| 52 | +def read_bird(bird_id: int, db: Session = Depends(get_db)): |
| 53 | + query = select(Bird).where(Bird.id == bird_id) |
| 54 | + found_bird = db.execute(query).scalar_one() |
| 55 | + if found_bird is None: |
| 56 | + raise HTTPException(status_code=404, detail="Bird not found") |
| 57 | + return found_bird |
| 58 | + |
| 59 | + |
| 60 | +@app.put("/birds/{bird_id}", response_model=BirdResponse) |
| 61 | +def update_bird(bird_id: int, bird: BirdUpdate, db: Session = Depends(get_db)): |
| 62 | + query = select(Bird).where(Bird.id == bird_id) |
| 63 | + found_bird = db.execute(query).scalar_one() |
| 64 | + if found_bird is None: |
| 65 | + raise HTTPException(status_code=404, detail="Bird not found") |
| 66 | + found_bird.name = bird.name |
| 67 | + db.commit() |
| 68 | + db.refresh(found_bird) |
| 69 | + return found_bird |
| 70 | + |
| 71 | + |
| 72 | +@app.delete("/birds/{bird_id}", response_model=dict) |
| 73 | +def delete_bird(bird_id: int, db: Session = Depends(get_db)): |
| 74 | + query = select(Bird).where(Bird.id == bird_id) |
| 75 | + found_bird = db.execute(query).scalar_one() |
| 76 | + if found_bird is None: |
| 77 | + raise HTTPException(status_code=404, detail="Bird not found") |
| 78 | + db.delete(found_bird) |
| 79 | + db.commit() |
| 80 | + return {"message": "Bird deleted successfully"} |
0 commit comments