apispec-webframeworks icon indicating copy to clipboard operation
apispec-webframeworks copied to clipboard

Only single path added for Flask API MethodViews

Open lafrech opened this issue 5 years ago • 10 comments

Issue by mathewmarcus Thursday Jan 18, 2018 at 21:14 GMT Originally opened as https://github.com/marshmallow-code/apispec/issues/181


The Flask documentation gives a use case - for RESTful APIs - where a single method view can be added under multiple URL rules. The following code snippet is provided as an example.

class UserAPI(MethodView):

    def get(self, user_id):
        if user_id is None:
            # return a list of users
            pass
        else:
            # expose a single user
            pass

    def post(self):
        # create a new user
        pass

    def delete(self, user_id):
        # delete a single user
        pass

    def put(self, user_id):
        # update a single user
        pass

user_view = UserAPI.as_view('user_api')
app.add_url_rule('/users/', defaults={'user_id': None},
                 view_func=user_view, methods=['GET',])
app.add_url_rule('/users/', view_func=user_view, methods=['POST',])
app.add_url_rule('/users/<int:user_id>', view_func=user_view,
                 methods=['GET', 'PUT', 'DELETE'])

If we define the following apispec and add the above view function like so

spec = APISpec(
    title='Swagger Petstore',
    version='1.0.0',
    plugins=[
        'apispec.ext.flask',
        'apispec.ext.marshmallow',
    ],
)

with app.test_request_context():
    spec.add_path(view=user_view)

only one of the above paths would be included in the generated apispec.

Looking at the apispec.ext.flask module, it seems that this behavior is a result of line 92 in the _rule_for_view function.

    # WARNING: Assume 1 rule per view function for now
    rule = current_app.url_map._rules_by_endpoint[endpoint][0]

Given the comment, it seems like this behavior is expected. Is there any interest in/intent to modify this to enable all of the paths to be added to the apispec in the above situation?

lafrech avatar Nov 03 '18 14:11 lafrech