POST 请求
需要首先定义
参数模型
from fastapi import FastAPI from pydantic import BaseModel import uvicorn # 声明参数模型 class Item(BaseModel): name: str description: str = None app = FastAPI() # 接受 POST 类型 @app.post("/") async def read_item(item: Item): # 参数类型是 return item if __name__ == '__main__': uvicorn.run( app = app, host = "127.0.0.1", port = 80, )
参数模型
# 导入模型类 from pydantic import BaseModel class Item(BaseModel): # 必要参数 name: str # 可选参数 description: str = None
参看文档
http://127.0.0.1/docs
请求测试
import requests url = "http://127.0.0.1" data = { "name" : "bigdataboy", "description": "", } r = requests.post(url=url,json=data) print(r.json())
高级用法
与
路径参数
一起使用
from fastapi import FastAPI from pydantic import BaseModel import uvicorn # 声明参数类 class Item(BaseModel): name: str description: str = None app = FastAPI() @app.post("/user/{id}") # 路径参数 async def read_item(id: int,item: Item): return {"id": id, **item.dict()} if __name__ == '__main__': uvicorn.run( app = app, host = "127.0.0.1", port = 80, )
版权声明:《 【FastAPI】 POST 方法 》为明妃原创文章,转载请注明出处!
最后编辑:2020-5-27 09:05:34