fastapi-boilerplate/app/main.py

71 lines
1.4 KiB
Python
Raw Normal View History

2023-08-10 22:46:36 +02:00
from fastapi import Depends, FastAPI
from fastapi.middleware.cors import CORSMiddleware
from sqlalchemy.orm import Session
from schemas import schemas
import database
import crud
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"]
)
# Dependency
def get_db():
db = database.SessionLocal()
try:
yield db
finally:
db.close()
@app.get("/")
async def root():
return {"message": "Hello World"}
@app.get("/items/{item_id}", response_model=schemas.Item)
async def get_item(
*,
db: Session = Depends(get_db),
item_id: int
):
2023-08-10 22:46:36 +02:00
return crud.item.get(db, item_id)
@app.get("/items/", response_model=list[schemas.Item])
async def get_items(
skip: int = 0,
limit: int = 100,
db: Session = Depends(get_db)
):
2023-08-10 22:46:36 +02:00
return crud.item.get_multi(db, skip=skip, limit=limit)
@app.post("/items/", response_model=schemas.Item)
async def create_item(
item: schemas.ItemCreate,
db: Session = Depends(get_db)
):
2023-08-10 22:46:36 +02:00
return crud.item.create(db=db, item=item)
@app.put("/items/{item_id}", response_model=schemas.ItemUpdate)
async def update_item(
item: schemas.ItemUpdate,
db: Session = Depends(get_db)
):
2023-08-10 22:46:36 +02:00
return crud.item.update(db=db, item=item)
@app.delete("/items/{item_id}")
async def delete_item(
*,
item: schemas.ItemUpdate,
db: Session = Depends(get_db),
item_id: int
):
2023-08-10 22:46:36 +02:00
return crud.remove(item_id)