FastAPI 是用来构建 API 服务的一个高性能框架。基于 Starlette 和 Pydantic,是 FastAPI 如此高性能的重要原因。
1)安装 python环境(Python 3.6 及以上版本)
2)安装 FastAPI
pip install fastapi
eg:
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI() //构建FastAPI对象
class User(BaseModel): //定义类
id: int
name: str
friends: list
//以下三个路由(两个采用Get请求的路径,一个采用put):
@app.get("/")
def index():
return {"admin": "welcome to FastAPI"}
@app.get("/users/{user_id}")
def read_user(user_id: int, name: str = None):
return {"user_id": user_id, "name": name}
@app.put("/users/{user_id}")
def update_user(user_id: int, user: User):
return {"user_name": user.name, "user_id": user_id}
运行: uvicorn main.app --port:8000 --reload
客户端:
http://127.0.0.1:8000
http://localhost:8000/users/5
http://localhost:8000/docs 查看此服务器对应的API文档
或
http://localhost:8000/redoc 以别一种方式显示对应的API文档
3)安装 pydantic,做 数据类型验证
pip install pydantic
Pydantic 主要用来做类型强制检查。参数赋值,不符合类型要求,就会抛出异常。
eg:
from pydan