ai_sandbox/api.py

49 lines
1.2 KiB
Python

from fastapi import FastAPI, HTTPException
from data import Recipe, Ingredient
import db
from psycopg2.errors import UniqueViolation
app = FastAPI()
conn = db.connect()
@app.put("/recipe")
def new_recipe(recipe: Recipe) -> Recipe | None:
try:
recipe = db.insert_recipe(recipe, conn)
except UniqueViolation:
raise HTTPException(status_code=400, detail="id conflict")
return recipe
@app.get("/recipe/{item_id}")
def get_recipe(item_id: int):
recipe = db.get_recipe(item_id, conn)
if not recipe:
raise HTTPException(
status_code=404,
detail=f"Recipe not found: id = {id}",
)
return recipe
@app.put("/ingredient")
def new_ingredient(ingredient: Ingredient) -> Ingredient | None:
try:
ingredient = db.insert_ingredient(ingredient, conn)
except UniqueViolation:
raise HTTPException(status_code=400, detail="id conflict")
return ingredient
@app.get("/ingredient/{item_id}")
def get_ingredient(id):
ingredient = db.get_ingredient(id, conn)
print(ingredient)
if not ingredient:
raise HTTPException(
status_code=404,
detail=f"Ingredient not found: id = {id}",
)
return ingredient