flask-smorest
flask-smorest copied to clipboard
Multiple representations question
Hello, I'm evaluating flask-smorest to see if it can fit our needs. I would like to set several representations (json,csv,xml, etc.) So far, it looks like json is the core representation. If I override the response decorator to handle my logic of fetching the correct representation, How can I adapt the representations so that it appears correctly in the doc as well (redoc or swagger). I guess to have to understand the whole swagger specs to adapt it accordingly, correct?
If it is not there yet, I think it would be nice feature to have a way to register representations at blueprint level or resource level depending on the context.
Hi.
I didn't get the time to check this. JSON format used to be totally hardcoded. I reworked the code to make it more generic so that JSON is hardcoded in a single place, which is better, and can be overridden.
Documenting multiformat resources should be achievable with limited pain (but don't take my word for it as, again, I didn't check). If anyone does it, please keep us posted here. I'm happy to add what's needed to the core.
Note that it may be easier to achieve if all resources return the same formats. Having per-format resources would be more work.
I'm considering adding a produces
or content_type
(I prefer to use OAS3 terminology) argument to response
.
If the schema is the same for all your response types, it might be enough to just allow this argument to be plural and document the schema for each response type.
I'm not fan of the "string or list of strings" arguments, but OTOH, if it is singular most of the times, it sucks to expect the user to enclose a single string in a list.
Same logic may apply at app level and perhaps blueprint level.
I've also evaluated flask-restx, and one thing they got right was just resource representations. Perhaps we can draw inspiration from what they have done, and apply it here, too. https://github.com/python-restx/flask-restx/blob/master/flask_restx/resource.py#L51
This is what I came up with, as work-around until there is a better feature to use for this:
@blp.response(Schema)
@blp.doc(responses={'200':{'description': 'OK', 'content':{
'text/yaml':{'schema': Schema},
'application/json':{'schema': Schema}
}}})
def get(self, node):
...
if 'application/json' == request.accept_mimetypes.best_match(['text/yaml', 'application/json'], default='text/yaml'):
# rely on flask-smorest to encode as json
return enc
return make_response(
yaml.safe_dump(Schema().dump(enc)),
[('content-type', 'text/yaml')]
)
which works reliably using swagger UI, as expected: