实例

创建一个fast_api_main.py文件,写入一下代码:

  1. from fastapi import FastAPI
  2. app = FastAPI()
  3. @app.get("/")
  4. def index():
  5. """
  6. 首页
  7. """
  8. return {"index": "我是首页"}
  9. @app.get("/book/{book_id}")
  10. def book(book_id: int, book_name: str = None):
  11. """
  12. 书籍📚
  13. 这里必须为book_id,与路径值保持一致,否则会被认为Query参数
  14. """
  15. return {
  16. "id": book_id,
  17. "book_name": book_name
  18. }

运行

  1. uvicorn fast_api_main:app --reload
  2. INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
  3. INFO: Started reloader process [54581] using statreload
  4. INFO: Started server process [54583]
  5. INFO: Waiting for application startup.
  6. INFO: Application startup complete.
  • fast_api_main为文件名
  • app为文件内通过app = FastAPI()创建的对象
  • —reload表示让服务器更新代码后重新启动

请求响应效果

  1. import requests
  2. print(requests.get("http://localhost:8000/").json())
  3. # {'index': '我是首页'}
  4. print(requests.get("http://localhost:8000/book/1/", params={"book_name": "数学之美"}).json())
  5. # {'id': 1, 'book_name': '数学之美'}
  6. print(requests.get("http://localhost:8000/book/1/").json())
  7. # {'id': 1, 'book_name': None}

交互式API文档

启动服务后

在浏览器访问:http://127.0.0.1:8000/docs

会看到由Swagger生成的API文档
image.png

在浏览器访问:http://127.0.0.1:8000/redoc

会看到由Redoc 📘生成的API文档
image.png

在浏览器访问:http://127.0.0.1:8000/openapi.json

会看到生成的JSON Schema信息,可用于导入Postman、Apifox等三方接口测试工具
image.png

小结

Fast API提供了简便的参数获取方式和动态路由的生成

在响应过程中,返回正常的python类型即可,Fast API会自动转译,无需像Django那样,通过Response模块

Fast API支持自动生成接口文档,且更灵活、可扩展