【FastAPI】 POST 方法

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

mark

请求测试

import requests

url = "http://127.0.0.1"

data = {
    "name" : "bigdataboy",
    "description": "",
}

r = requests.post(url=url,json=data)
print(r.json())

mark

高级用法

路径参数一起使用

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,
    )

mark

发表评论 / Comment

用心评论~