from fastapi import FastAPI from enum import Enum from pydantic import BaseModel from typing import Annotated from fastapi import FastAPI, File, UploadFile from pathlib import Path import shutil, uuid import uvicorn import os app = FastAPI() @app.get("/healthz") def health(): return {"repsonse_from_fastapi": "very very ok"} class ModelName(str, Enum): alexnet = "alexnet" resnet = "resnet" lenet = "lenet" @app.get("/models/{model_name}") async def get_model(model_name: ModelName): if model_name is ModelName.alexnet: return {"model_name": model_name, "message": "Deep Learning FTW!"} if model_name.value == "lenet": return {"model_name": model_name, "message": "LeCNN all the images"} return {"model_name": model_name, "message": "Have some residuals"} fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}] class Item(BaseModel): name: str description: str | None = None price: float tax: float | None = None @app.post("/items/") async def create_item(item: Item): item_dict = item.model_dump() if item.tax is not None: price_with_tax = item.price + item.tax item_dict.update({"price_with_tax": price_with_tax}) return item_dict @app.post("/files/") async def create_file(file: Annotated[bytes, File()]): return {"file_size": len(file)} UPLOAD_DIR = Path("/tmp/uploads") UPLOAD_DIR.mkdir(parents=True, exist_ok=True) @app.post("/uploadfile/") async def create_upload_file(file: UploadFile = File(...)): # avoid trusting user-supplied filenames ext = (Path(file.filename).suffix or ".bin").lower() safe_name = f"{uuid.uuid4().hex}{ext}" dest = UPLOAD_DIR / safe_name with dest.open("wb") as f: shutil.copyfileobj(file.file, f) return {"saved_as": str(dest)} if __name__ == "__main__": port = int(os.getenv("PORT", "7860")) uvicorn.run(app, host="0.0.0.0", port=port, reload=False)