flask-openapi3 icon indicating copy to clipboard operation
flask-openapi3 copied to clipboard

Add support for multiple custom JSON content types in the request body

Open joaopedroft opened this issue 1 year ago • 3 comments

From what I could understand the request body is limited to the use of application/json content-type. I believe that the use of custom content type should be supported e.g.:

OAS:

paths:
  /pet:
    put:
      tags:
        - pet
      summary: Update an existing pet
      description: Update an existing pet by Id
      operationId: updatePet
      requestBody:
        description: Update an existent pet in the store
        content:
          application/vnd.dog+json:
            schema:
              $ref: '#/components/schemas/Dog'
          application/vnd.cat+json:
            schema:
              $ref: '#/components/schemas/Cat'

Code:

class Dog(BaseModel):
    class Config:
        content_type = "application/vnd.dog+json"

class Cat(BaseModel):
    class Config:
        content_type = "application/vnd.cat+json"


@app.put('/pet')
def update_pet(body: Union[Dog, Cat]):
    if isinstance(body, Dog):
        ...
    else:
        ...

joaopedroft avatar Aug 16 '23 15:08 joaopedroft

If the body is not of type BaseModel, we must re-implement the data validation function (source code), it will be a lot of work.

So I suggest another way:

class UnionModel(BaseModel):
    __root__: Union[Dog, Cat]


@app.put('/pet')
def update_pet(body: UnionModel):
    print(body)
    print(type(body))
    return body.json()

luolingchun avatar Aug 17 '23 02:08 luolingchun

I understand thank you, I believe that I can work with the alternative.

joaopedroft avatar Aug 17 '23 10:08 joaopedroft

I want to work on this.

raisachatterjee avatar Aug 17 '23 11:08 raisachatterjee