Fastapi: How to declare Multiple type for request body?

Created on 22 Oct 2020  路  2Comments  路  Source: tiangolo/fastapi

class A:
class B:
class C:

@app.put("/test")
async def test(item: OptionalA]):
    return item

I want to allow class A,B,C for test path.

question

All 2 comments

I did not understand the problem here, but as far as I understand from the title you want to do this.

from fastapi import FastAPI, Body
from typing import Union
from pydantic import BaseModel


class User(BaseModel):
    name: str


class Item(BaseModel):
    size: int
    price: float


app = FastAPI()


@app.post("/multi/")
def process_things(body: Union[User, Item] = Body(..., example={"Create your own schema.": "here"})):
    return body

The reason that I used Body(..., example="here") is #1083, this is not a bug in FastAPI but Swagger can not document Union models properly right now, so you should create your own example if needed.

Yes, Thanks

Was this page helpful?
0 / 5 - 0 ratings