之前一直用Flask,今年看到这个FastAPI,感觉还不错,体验了下,很容易就入门。

FastAPI入门

开始学习

FastAPI特点

官方描述

从官方的描述来看,有以下特点:

  • 高性能,与NodeJS和Go相当,最快的 框架之一。
  • 快速编写代码:将功能开发的速度提高大约200%至300%。
  • 更少的错误:减少约40%的人为错误(开发人员)
  • 直观:强大的编辑器支持,花费调试时间更少。
  • 简易:旨在易于使用和学习, 减少阅读文档的时间。
  • 简短:减少代码重复
  • 稳定健壮:获取可用于生产环境的代码, 具有自动交互式文档。
  • 标准化: 基于(并完全兼容)API的开放标准:OpenAPI(以前称为Swagger)和JSON模式。

 

版本要求

Python 3.6+

 

安装

$ pip install fastapi
$ pip install uvicorn

 

入门例子

 

# main.py
from fastapi import FastAPI
 = 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}

 

如果是异步,可以这么写:

# main.py
from fastapi import FastAPI
app = FastAPI()@app.get("/")
async def read_root():    return {"Hello": "World"}
@app.get("/items/{item_id}")
async def read_item(item_id: int, q: str = None):    return {"item_id": item_id, "q": q}

 

启动方式

 

$ uvicorn main:app --reload --port 18080

参数说明:

 

  • main: main.py 文件(也可理解为Python模块).
  • app: main.py 中app = FastAPI()语句创建的app对象.
  • --reload: 在代码改变后重启服务器,只能在开发的时候使用
  • 默认端口是8000,可以使用`--port`来指定其他端口

 

启动后输出:

INFO:     Uvicorn running on http://127.0.0.1:18080 (Press CTRL+C to quit)
INFO:     Started reloader process [19071]
INFO:     Started server process [19091]
INFO:     Waiting for application startup.
INFO:     Application startup complete.

 

可以看到服务已经启动,访问路径是http://127.0.0.1:18080 。

 

检查服务是否正常

 

打开你的浏览器,输入 http://127.0.0.1:18080 。

你将会看见JSON响应:

{"hello": "world"}

 

 


 

更简单的启动

 

#myapi.py
import uvicorn
if __name__ == "__main__":
    uvicorn.run("myapi:app", host="127.0.0.1", port=18080, log_level="info")

 

通过引入uvicorn库,那么我们就可以跟之前运行脚本的方式一样执行脚本就可以了。

 

python3 myapi.py

 

查看生成API的文档

  • Swagger UI风格文档:打开你的浏览器,输入 http://127.0.0.1:18080/docs 。

 

 

  • ReDoc风格文档打开你的浏览器,输入 http://127.0.0.1:18080/redoc 。

 

 

由于对外暴露文档,也是比较危险,那么我可不可以关闭API文档,答案是可以的,我们可以加一些参数来屏蔽它。

 

app = FastAPI(docs_url=None, openapi_url=None, redoc_url=None)

 

当你再次访问文档链接,会提示:

{"detail":"Not Found"}

 

 

是不是很简单,通过这个框架可以快速的完成接口。当然它还有更多的特性,这里就不展开了,有兴趣的可以自行查阅深入学习。

胜象大百科