A concise cheatsheet for FastAPI, a fast and modern web framework for building APIs with Python 3.7+.
from fastapi import Form
@app.post("/login")
def login(user: str = Form(...)):
return {"user": user}
from fastapi import UploadFile, File
@app.post("/upload")
def upload(f: UploadFile = File(...)):
return {"filename": f.filename}
from fastapi import Header, Cookie
@app.get("/info")
def info(ua: str = Header(None)):
return {"UA": ua}
@app.middleware("http")
async def log_req(req, call_next):
res = await call_next(req)
return res
from fastapi import Depends
def auth(token: str = ""):
if token != "xyz": raise HTTPException(401)
return True
@app.get("/secure")
def secure(_: bool = Depends(auth)):
return {"secure": True}