软件测试者一定要的微信公众号 软件测试技术 ,每天有大量干货更新,不仅仅有测试技术哦~
官网介绍如下:
FastAPI framework, high performance, easy to learn, fast to code, ready for production.
FastAPI框架,高性能,易于学习,代码快速,可投入生产
版本 python3.6+
pip install fastapi
pip install uvicorn
创建一个main.py的文件
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "q": q}
运行命令 uvicorn main:app --reload
$ uvicorn main:app --reload
InFo: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
InFo: Started reloader process using
InFo: Started server process
InFo: Waiting for application startup.
InFo: Application startup complete.
登录http://127.0.0.1:8000/
,返回:
{"Hello":"World"}
登录http://127.0.0.1:8000/items/9527?q=1234
,返回:
{"item_id":9527,"q":"1234"}
登录http://127.0.0.1:8000/docs
,可以看到自动交互API文档:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-FurVBujH-1591090260868)(https://i.loli.net/2020/06/01/u6PBzxEbS9dmYw1.png)]
如果运行的时候增加,--reload
命令参数,则API文档自动会随着定义而更新。例如增加put请求:
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
is_offer: bool = None
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "q": q}
@app.put("/items/{item_id}")
def update_item(item_id: int, item: Item):
return {"item_name": item.name, "item_id": item_id}
登录 http://127.0.0.1:8000/redoc
,备份Api文档,可以实时看到文档变化:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-MPxqSMCz-1591090260869)(https://i.loli.net/2020/06/01/fniypldOPUbjRSN.png)]
登录http://127.0.0.1:8000/docs
,点击对应的接口下的Try it out
,就可以调试接口:
官方对性能解释如下:
Independent TechEmpower benchmarks show FastAPI applications running under Uvicorn as one of the fastest Python frameworks available, only below Starlette and Uvicorn themselves (used internally by FastAPI).
独立机构 TechEmpower 所作的基准测试结果显示,基于 Uvicorn 运行的 FastAPI 程序是 最快的 Python web 框架之一,仅次于 Starlette 和 Uvicorn 本身(FastAPI 内部使用了它们)