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)