文件名称 | 版本号 | 作者 | 版本 | |
---|---|---|---|---|
写Python API好简单,非Gen | v1.0.0 | 学生宫布 | 8416837 | Python 3.8 FastAPI (0.1.0) |
FastAPI
Demo
- 这里假设你已经会使用一款IDE(集成开发环境)或命令行
依赖
- 安装依赖
用的工具可能是pip
|pip3
执行pip3 --help
试一下。
如果以下安装太慢,请使用国内镜像。
pip3 install fastapi
# ASGI 服务:uvicorn:
pip3 install uvicorn
代码
- 主类 main.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/{name}")
def read_root(name):
return {"Hello": "World" + name}
@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
【注意】IDE执行上述命令可能因配置问题而闪退
启动成功:
调用
- 接口1
localhost:8000/_name
- 接口2
localhost:8000/items/3001?q=狗
文档
- FastAPI自带文档,地址是
http://localhost:8000/docs
- 同时自带redoc文档,访问地址是
http://localhost:8000/redoc
炫技
参数验证
Json参数的接口
- 代码比上述代码复杂一点点
- 服务端:
from pydantic import BaseModel
from fastapi import FastAPI
app = FastAPI()
class Dog(BaseModel):
nick_name: str
tooth: int
sex: int
age_month: float
@app.post("/dog")
def read_item(dog: Dog):
print(dog)
return dog
- 客户端:
HTTPClient传json参数,以期获得响应参数
import requests
url = "http://localhost:8000/dog"
params = {"nick_name":"QWo","sex":1,"tooth":34, "age_month": 13.5}
res = requests.post(url,json=params)
res.json()
执行请求,响应没问题:
测试功能
- 框架底层做了封装,使用Python HTTPClient随手测试一下
import requests
url = "http://localhost:8000/dog"
params = {"nick_name":"QWo","sex":1,"tooth":"99"}
res = requests.post(url,json=params)
res.json()
- 故意传错参数试试:
↑自动将字符串强转成了数字。 - 改成非数字,报错了:
- 漏传参数,友好提示:
↑age_month参数漏传了。 - 将参数改为非必传(not required):
加上= None
- 谢谢!更多炫技待续。。。