FastAPI 是一个用于构建 API 的现代、快速(高性能)的 web 框架,使用 Python 3.6+ 并基于标准的 Python 类型提示。
依赖
Python3.6及更高版本
安装
pip install fastapi
需要一个ASGI服务器,生产环境可以使用Uvicorn 或者 Hypercorn
pip install uvicorn
使用
1 from typing import Optional 2 3 from fastapi import FastAPI 4 5 app = FastAPI() 6 7 8 @app.get("/") 9 def read_root(): 10 return {"Hello": "World"} 11 12 13 @app.get("/items/{item_id}") 14 def read_item(item_id: int, q: Optional[str] = None): 15 return {"item_id": item_id, "q": q}
启动:uvicorn main:app --reload
uvicorn main:app 解释
访问:http://127.0.0.1:8000/items/1?q=wq 返回结果如下
{"item_id":1,"q":"wq"}
通过 / 和 /items/{item_id} 接收HTTP请求
以上路径都接受GET操作
/items/{item_id} 路径有一个路径参数item_id并且应该为int类型
/items/{item_id} 路径有个可选str类型的查询参数q
交互式API文档
http://127.0.0.1:8000/docs 会自动生成交互式API文档(由Swagger生成)
「Try it out」按钮,之后你可以填写参数并直接调用 API:
可选API文档
访问: http://127.0.0.1:8000/redoc (由ReDoc生成)
菜鸟级入门FastAPI,还需小伙伴们自行搭建,多写多多练,此文仅供大家参考
good lucky !
原文:https://www.cnblogs.com/tress/p/Trees.html