From @amanb answer I made my api return a yaml file, without making any requests.
According to documentation of flask restplus (or, the most recent fork, flask restx) it is possible to export the Swagger specififcations corresponding to your API using:
from flask import json
from myapp import api
print(json.dumps(api.__schema__))
So, instead of using requests
I preferred to use api.__schema__
.
As my goal is to provide the file for download at the time of the request, it is necessary to use the send_file
function of Flask
. In addition, this file can be later deleted from the directory so we can use the after_this_request
decorator of Flask
to invoke the annotated function that will delete the file. The full code:
import os
import json
import yaml
from flask import Flask, after_this_request, send_file, safe_join, abort
from flask_restplus import Resource, Api
from flask_restplus.api import Swagger
app = Flask(__name__) # Create a Flask WSGI application
api = Api(app) # Create a Flask-RESTPlus API
@api.route('/hello') # Create a URL route to this resource
class HelloWorld(Resource): # Create a RESTful resource
def get(self):
return {'hello': 'world'}
@api.route('/swagger.yml')
class HelloWorld(Resource):
def get(self):
data = json.loads(json.dumps(api.__schema__))
with open('yamldoc.yml', 'w') as yamlf:
yaml.dump(data, yamlf, allow_unicode=True, default_flow_style=False)
file = os.path.abspath(os.getcwd())
try:
@after_this_request
def remove_file(resp):
try:
os.remove(safe_join(file, 'yamldoc.yml'))
except Exception as error:
log.error("Error removing or closing downloaded file handle", error)
return resp
return send_file(safe_join(file, 'yamldoc.yml'), as_attachment=True, attachment_filename='yamldoc.yml', mimetype='application/x-yaml')
except FileExistsError:
abort(404)
if __name__ == '__main__':
app.run(debug=True)