FastAPI上传POST多个对象BaseModel数据JSON,python

Posted zhangphil

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了FastAPI上传POST多个对象BaseModel数据JSON,python相关的知识,希望对你有一定的参考价值。

FastAPI上传POST多个对象BaseModel数据JSON,python

from typing import Optional

import uvicorn
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()


class Person(BaseModel):
    name: str
    desc: Optional[str] = None


class User(BaseModel):
    username: str
    age: Optional[int] = 0


@app.post("/item/item_id")
async def item(item_id: int, person: Person, user: User):
    results = "item_id": item_id, "person": person, "user": user
    return results


if __name__ == '__main__':
    uvicorn.run(app=app, host="0.0.0.0", debug=True)

在postman里面构造多个对应的json数据对象:

如果上传的既有JSON也有其他基本类型时候,比如一个count=10,则需要定义 Body():

from typing import Optional

import uvicorn
from fastapi import FastAPI, Body
from pydantic import BaseModel

app = FastAPI()


class Person(BaseModel):
    name: str
    desc: Optional[str] = None


class User(BaseModel):
    username: str
    age: Optional[int] = 0


@app.post("/item/item_id")
async def item(item_id: int, person: Person, user: User, count: int = Body()):
    results = "item_id": item_id, "person": person, "user": user, "count": count
    return results


if __name__ == '__main__':
    uvicorn.run(app=app, host="0.0.0.0", debug=True)

以上是关于FastAPI上传POST多个对象BaseModel数据JSON,python的主要内容,如果未能解决你的问题,请参考以下文章

FastAPI上传POST嵌套JSON对象及List列表BaseModel,python

上传多个文件 UploadFiles FastAPI

FastAPI接受POST上传文件并保存本地,python

FastAPI学习-7.POST请求body-多个参数

使用 curl 将文件上传到 FastAPI 端点 - 307 临时重定向

如何在fastapi中获取多个表单输入字段作为字典?