FastAPI接受post上传JSON对象BaseModel,python

Posted zhangphil

tags:

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

FastAPI接受post上传JSON对象BaseModel,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
    age: int
    year: Optional[int] = None


@app.post("/item")
async def create_item(p: Person):
    return p


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

用postman往127.0.0.1:8000/item地址post一个json对象,注意里面有些k-v特意缺失:

如果想把Person放入到一个json的key值里面:

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
    age: Optional[int] = 0
    year: Optional[int] = None


@app.post("/item")
async def create_item(person: Person = Body(embed=True)):
    return person


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

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

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

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

FastAPI学习-6.POST请求 JSON 格式 body

FastAPI/Pydantic 接受任意发布请求正文?

如何使用 pydantic/fastapi 接受具有数组\单个项目的单个路由对象?

上传多个文件 UploadFiles FastAPI