环境安装

以 uvicorn 作为服务器,有两种安装方式

  1. # 快速安装 (推荐使用)
  2. pip3 install fastapi[all]
  3. # 分步安装
  4. pip3 install fastapi
  5. pip3 install pydantic
  6. pip3 install uvicorn[standard]

调试使用

导入模块

  1. from fastapi import FastAPI

实例化

  1. app = FastAPI()
  2. FastAPI() 中参数:
  3. debug: bool = False,
  4. routes: Optional[List[BaseRoute]] = None,
  5. title: str = "FastAPI", # 修改 docs 文件 title
  6. description: str = "",
  7. version: str = "0.1.0",
  8. openapi_url: Optional[str] = "/openapi.json",
  9. openapi_tags: Optional[List[Dict[str, Any]]] = None,
  10. servers: Optional[List[Dict[str, Union[str, Any]]]] = None,
  11. dependencies: Optional[Sequence[Depends]] = None,
  12. default_response_class: Type[Response] = Default(JSONResponse),
  13. docs_url: Optional[str] = "/docs",
  14. redoc_url: Optional[str] = "/redoc",
  15. swagger_ui_oauth2_redirect_url: Optional[str] = "/docs/oauth2-redirect",
  16. swagger_ui_init_oauth: Optional[Dict[str, Any]] = None,
  17. middleware: Optional[Sequence[Middleware]] = None,
  18. exception_handlers: Optional[
  19. Dict[
  20. Union[int, Type[Exception]],
  21. Callable[[Request, Any], Coroutine[Any, Any, Response]],
  22. ]
  23. ] = None,
  24. on_startup: Optional[Sequence[Callable[[], Any]]] = None,
  25. on_shutdown: Optional[Sequence[Callable[[], Any]]] = None,
  26. openapi_prefix: str = "",
  27. root_path: str = "",
  28. root_path_in_servers: bool = True,
  29. responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,
  30. callbacks: Optional[List[BaseRoute]] = None,
  31. deprecated: Optional[bool] = None,
  32. include_in_schema: bool = True,

如无特殊情况,保持参数为默认设置即可

映射路由

  1. @app.get("/get")
  2. @app.post("/post")
  3. @app.put("/put")
  4. @app.delete("/delete")
  5. @app.options("/options")
  6. @app.head("/head")
  7. @app.patch("/patch")
  8. @app.trace("/trace")

必须以 ”/“ 开始,最好也以 ”/“ 作为结尾,保证路由地址完整性

业务函数

  1. @app.get('/')
  2. def get_msg():
  3. return {'msg': 'kumazz's fastapi'} # return 可以返回任意类型的值

启动服务

  1. uvicorn main:app --reload # main 指的是 运行的 python 程序,app 指的是 实例化后的对象名称
  2. --reload 的作用是改动了代码会自动识别,然后重新启动(生产环境不建议使用,消耗性能)
  3. --host 0.0.0.0
  4. --port 8080
  5. nohup uvicorn main:app --host 0.0.0.0 --port 8080

访问结果

  1. http://127.0.0.1:8080/ # 案例中定义的路由,@app.get('/')
  2. http://127.0.0.1:8080/docs # swagger 接口文档
  3. http://127.0.0.1:8080/redoc # redoc 接口文档
  4. http://127.0.0.1:8080/openapi.json # 查看 json 文档,可以使用它自动生成与你的 API 进行通信的客户端代码,都是基于 openapi

直接运行

  1. import uvicorn
  2. if __name__ == '__main__':
  3. uvicorn.run(app='main:app', host='127.0.0.1', port=8080, reload=True, debug=True)
  4. run 的其他参数:
  5. uvicorn/config.py:119

API 文档

  1. @app.get("/items/", include_in_schema=False)
  2. async def read_items():
  3. return [{"item_id": "Foo"}]

所有的路由默认是生成 API 文档的,如果不想添加到 API 文档,可以设置 include_in_schema=False