swagger-codegen icon indicating copy to clipboard operation
swagger-codegen copied to clipboard

[Python] Issue with Multipart/Form-Data Requests

Open jgpeiro opened this issue 2 years ago • 0 comments

Description

I am encountering an issue with Swagger UI when using the Python generated code to perform multipart/form-data requests. The server receives que request, but it fails validating the data. This happens both using the client code or the curl command.

http://localhost:8080/test validation error: '{\r\n  "name": "string",\r\n  "age": 0\r\n}' is not of type 'object' - 'body'
127.0.0.1 - - [12/Dec/2023 12:46:37] "POST /test HTTP/1.1" 400 -

Looking at the examples in the documentation, the root object is called body, and the file is binary so it is encoded octet-stream by default, so I don't see any errors here, but for some reason the server cannot validate it correctly .

Swagger-codegen version

https://editor-next.swagger.io/ OS: Ubuntu 22.04.2 LTS Python: Python 3.10.12 Python packages: swagger-ui-bundle 0.0.9 connexion 2.14.2 urllib3 2.1.0 Flask 2.2.5 six 1.16.0

Swagger declaration file content
openapi: 3.0.1
info:
  title: Test
  version: 1.0.0
servers:
  - url: http://localhost:8080
paths:
  /test:
    post:
      requestBody:
        content:
          multipart/form-data:
            schema:
              type: object
              properties:
                body:
                  type: object
                  properties:
                    name:
                      type: string
                    age:
                      type: integer
                file:
                  type: string
                  format: binary
      responses:
        '200':
          description: OK
Steps to reproduce

It can be reproduced from python code or curl command:

from swagger_client.configuration import Configuration
from swagger_client.rest import ApiException
from swagger_client.api_client import ApiClient
from swagger_client.api.default_api import DefaultApi
from swagger_client.models import TestBody

configuration = Configuration()
configuration.host = "http://localhost:8080"

api_client = ApiClient(configuration)
api_instance = DefaultApi(api_client)

body = TestBody(
    name="test", 
    age=1
)
file="sample.bin"
try:
    api_response = api_instance.test_post(
        body=body.to_str(), # using .to_dict() method causes a TypeError exception on client side.
        file=file
    )
    print(api_response)
except ApiException as e:
    print("Exception when calling DefaultApi->test_post: %s\n" % e)
curl -X 'POST' \
  'http://localhost:8080/test' \
  -H 'accept: */*' \
  -H 'Content-Type: multipart/form-data' \
  -F 'body={
  "name": "string",
  "age": 0
}' \
  -F '[email protected];type=application/octet-stream'

jgpeiro avatar Dec 12 '23 12:12 jgpeiro