2

In the OA3 documentation it states that you can have multiple response content types like this:


paths:
  /users:
    get:
      summary: Get all users
      responses:
        '200':
          description: A list of users
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ArrayOfUsers'
            application/xml:
              schema:
                $ref: '#/components/schemas/ArrayOfUsers'
            text/plain:
              schema:
                type: string

How do I specify that I want to return a specific content type in the controller of a generated python-flask app?

Here's the response portion of the spec that I am trying to implement:

      responses:
        "200":
          description: successful operation
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/CoordinateResponse"
            text/csv:
              schema:
                type: string

I've got a string variable called response_value in my controller with the contents of a CSV file.

I tried a bunch of different things, such as

return response_value, 200, {'Content-Type': 'text/csv; charset=utf-8'}

produces a response with Content-Type: application/json

and

from connexion.lifecycle import ConnexionResponse
return ConnexionResponse(body=response_value, status_code=200, content_type='text/csv')

produces no response

and

from flask import Response
return Response(response_value, mimetype='text/csv')

produces no response

and

from flask import make_response
output = make_response(response_value)
output.headers["Content-type"] = "text/csv"
return output

produces no response

How do I get it to respond with Content-Type: text/csv?

Mike Furlender
  • 3,869
  • 5
  • 47
  • 75

1 Answers1

0

Finally got it working like this:

            from io import BytesIO
            mem = BytesIO()
            mem.write(response_value.encode('utf-8'))
            mem.seek(0)

            from flask import send_file
            return send_file(
                mem,
                as_attachment=True,
                attachment_filename="somefile.csv",
                mimetype='text/csv'
            )

As soon as I post a stackoverflow question I stumble on the answer. Story of my life.

Mike Furlender
  • 3,869
  • 5
  • 47
  • 75
  • what is `response_value` here? I am having the problem with returning XML via get request :( – Zafar Sep 15 '20 at 05:51
  • @Zafar `response_value` is just my CSV data. I'm guessing you can do the same thing for XML using `mimetype='text/xml'` or `mimetype='application/xml'` – Mike Furlender Sep 16 '20 at 15:42