openapi-python-client icon indicating copy to clipboard operation
openapi-python-client copied to clipboard

`File.file_name` marked as `Optional` but is required when used in `multipart/form-data`

Open johnthagen opened this issue 1 year ago • 1 comments

Describe the bug

In types.py:

https://github.com/openapi-generators/openapi-python-client/blob/0399271be4eb012f83ac3023939ff48e364634e9/openapi_python_client/templates/types.py.jinja#L24

file_name is marked Optional, so it seems like the user could omit it. But if they do to a multipart/form endpoint, backends such as DjangoRestFramework will return:

Status Code: 400 (Bad Request)
Content    : {"file":["The submitted data was not a file. Check the encoding type on the form."]}

This means that users will not get a type checking error if they forget to include a file_name in this scenario.

It seems like perhaps a MultipartFile type is needed to be used to correctly model this?

@define
class MultipartFile:
    """Contains information for multipart file uploads"""

    payload: BinaryIO
    file_name: str
    mime_type: Optional[str] = None

    ...

OpenAPI Spec File

  /upload/:
    post:
      operationId: upload
      requestBody:
        content:
          multipart/form-data:
            schema:
              $ref: '#/components/schemas/UploadRequest'
        required: true

components:
  schemas:
    UploadRequest:
      type: object
      properties:
        file:
          type: string
          format: binary
      required:
      - file

Desktop (please complete the following information):

  • OS: macOS 13.6.4
  • Python Version: 3.12.0
  • openapi-python-client version: 0.16.1

Additional context

The generated Swagger UI page for this endpoint looks like:

Screenshot 2024-03-08 at 8 06 45 AM

Backend versions:

  • Django 4.2.11
  • djangorestframework 3.14.0
  • drf-spectacular 0.27.1

johnthagen avatar Mar 08 '24 13:03 johnthagen

@dbanty I just hit this again. If a user forgets to include a file_name and use the client to upload to a multi-part endpoint, the data will be sent incorrectly (in my case when I just hit this, the data was sent as a str instead of streamed as a binary file-like object). The data arrives at the server incorrectly.

  • openapi-python-client 0.22.0
  • httpx 0.27.2
  • Python 3.12.2

johnthagen avatar Dec 12 '24 14:12 johnthagen