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