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
?
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.