miguelgrinberg / APIFairy

A minimalistic API framework built on top of Flask, Marshmallow and friends.
MIT License
323 stars 30 forks source link

authentication for api specification #58

Closed AdamVerner closed 2 years ago

AdamVerner commented 2 years ago

i would love to expose the API documentation out, but only for authenticated users.

currently hacked it around like this

import apifairy as apifairy_module

template_folder = os.path.join(os.path.dirname(apifairy_module.__file__), 'templates')
apifairy_bp = Blueprint('apifairy', 'apifairy', template_folder=template_folder)

@apifairy_bp.route('/docs/api.json', endpoint='json')  # dont actually care about json, just need the endpoint
@login_required
def apifairy_docs():
    return dumps(apifairy.apispec), 200, {'Content-Type': 'application/json'}

@apifairy_bp.route('/docs/api', endpoint='docs')
@login_required
def apifairy_docs():
    # noinspection PyUnresolvedReferences
    return render_template(f'apifairy/{apifairy.ui}.html', title=apifairy.title, version=apifairy.version)

app.register_blueprint(apifairy_bp)

it would be nice, if the render functions json and doc from APIFairy.create_app were exposed (even as underscore functions) so they could be used from the outside to add the required authentication, caching and so on.

miguelgrinberg commented 2 years ago

I don't like the idea of exposing the endpoints, because they are extremely basic and do not support any configuration. What I think makes more sense is to allow the application to attach decorators to them, which is a pattern that already exists in Flask with the class-based views.

I have added the APIFAIRY_UI_DECORATORS and APIFAIRY_APISPEC_DECORATORS for this purpose. Both are lists of decorators that are applied in the order given to the default endpoints.