问题库 Python how-to

Python FastAPI 如何写一个接口

快速答案

定义 app 和路径函数,使用 uvicorn 启动服务。

py
from fastapi import FastAPI
app = FastAPI()
@app.get('/health')
def health():
    return {'ok': True}

使用要点

  • 请求接口时设置超时,并区分连接失败、HTTP 错误和业务错误。
  • 重试只适合幂等请求,写入类接口要避免重复提交。

相关内容