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)