2 篇文章带有标签 “api-design”

FastAPI 开发 RESTAPI 实践

首页

重定向到 Swagger UI

@app.get("/", include_in_schema=False)
async def index():
    return RedirectResponse('/docs', status_code=303)

使用 route 的 docstring 作为首页内容

@app.get("/", response_class=HTMLResponse, include_in_schema=False)
async def index():
    # 需要过滤的路由
    filted_routes = [
        "/openapi.json",
        "/docs",
        "/docs/oauth2-redirect",
        "/redoc",
        "/static",
        "/"
    ]
    
    routes = []
    for route in app.routes:
        if route.path not in filted_routes:
// ...

Markdown to HTML

安装

pip install markdown

使用

FastAPI : Request File and Form(BaseModel)

两种方法

(file: UploadFile = File(...), mask: Json = Form(default=None))

from pydantic import BaseModel, Json, ValidationError
from fastapi import APIRouter, File, UploadFile, HTTPException, Form, Depends

class Box(BaseModel):
    x: int
    y: int
    w: int
    h: int

router = APIRouter()

@router.post("/test")
async def test(file: UploadFile = File(...), 
               mask: Json = Form(default=None), 
               n: int = Form(default=0)) -> str:
// ...

(file: UploadFile = File(...), mask: Box = Depends(validate_json(Box)))