Search code examples
pythonflaskflask-restful

Flask API using custom Resource subclass methods


I've been using the following approach to build Flask rest API (this is just a brief example to help you understand my question):

from flask_restful import Resource, Api
from models.user import User, UserSchema
from flask import Blueprint, request, make_response

user_service_blueprint = Blueprint('user_service', __name__)
user_schema = UserSchema()
service = Api(user_service_blueprint)

class UserResource(Resource):
    def get(self, id):
        # do some work here
        ...

    def patch(self, id):
        # do some work here
        ...

    def delete(self, id):
        ...

service.add_resource(UserResource, '/users/<int:id>')

I want to add a new UserResource GET method called get_only_registered_users(self, id: int) (doesn't matter) and add this to the service with another endpoint, namely /registered_user/<int: id>.

I can reach my goal by creating a separate Resource subclass, but I am wondering if it can be done by just adding a new method to the UserResource class and adding it to the service without creating a separate Resource subclass for just one method. Maybe I can use something like service.add(UserResource.custom_method, '/custom_endpoint/<int:user_id')?


Solution

  • Let's try to specific the endpoint like:

    def get(cls, user_id):
        if request.endpoint == 'registered_users':
            // Your logic
        else:
            // Your logic
    .....
    service.add_resource(UserResource, '/users/<int:id>', endpoint='users')
    service.add_resource(UserResource, '/registered_users/<int:id>', endpoint='registered_users')