connexion
connexion copied to clipboard
Returning JSON and HTML
Hi,
based on the requested content type I want my API to return either JSON or HTML. The latter is for non technical people to allow them some basic browsing of the API.
I don't understand how to do the mapping between the yaml file and the Python functions. The "produces" directive of the Open API spec is too wide. Also it is not an aspect of the API definition. The information "produces application/json and text/html" is correct and actually precise enough.
My current approach (theoretical): YAML path /pets maps to function api.pets(). Here I would inspect the incoming (requested) content type and then delegate to either api.pets_json() or api.pets_html().
There must be a better way to do this. Some decorator magic maybe?
Many thanks
What kind of navigation do you wish to implement? Is the Swagger UI not enough?
It is inspired by the book "REST und HTTP" http://rest-http.info/
The idea is that JSON is just one of the possible output formats. Maybe there are other machines (in our legacy environment not unlikely) which prefer XML or even csv.
In our case it would be helpful to provide non technical people an idea of what is going over the wire. Also, it would be nice to to be able to send links like: this is the record of order 123456 (https://.../orders/123456)
In the meantime I have been thinking. I believe a custom return function would do the job. Depending on the the requested content type it would "jsonify" or render a html template. The actual business logic is for both use cases the same. It is just the output format which differs.
So if there is no special magic trick I would go with the custom render function and this question could be closed. Thanks for the good work guys.
Hi @samba2,
Seems like you want content negotiation. Unfortunately it is not supported by OpenAPI/Swagger 2.0 spec. Therefore Connexion does not support it either. The good news is that it has been added to the OpenAPI 3.0 and we should add support for that sometime in the future when it gets released.
Thank you for using Connexion. Let us know if you have more questions.
Hi @rafaelcaricio, Is there any update on supporting multiple return types?
can you even return html at all? I'm using text/html as a content type for the response and getting a json response.
@manoadamro I have only gotten connexion to return HTML by returning a flask Response object. I'm starting to think this is the only way to return anything but json.
def returns_html():
html = "<html><body>This is HTML</body></html>"
return Response(html, mimetype="text/html", status=400)
/Thing/:
get:
operationId: service.returns_html
responses:
"200":
description: html page
content:
text/html:
schema:
type: string
example: "<html/>"
Fixed since https://github.com/spec-first/connexion/pull/1588