Search code examples
pythonrestflask-restful

flask-restul nested resources


Im refactoring my rest api server to use Flask-RESTful, and im having some doubt about some particular cases where i need to get a list of resources that belong to another. Some thing like this:

/api/v1/users/john/orders

How would you design this? Because if I have a resource called Orders, I need to know from which user i have to get the orders from. But how can i let the resource know about the user? i dont see any __ init __ method where i can specify parameters to the resources.

I thought about doing something like this when registering the Orders resource:

api.add_resources(Orders, '/api/v1/users/<string:username>/orders')

But the how can i access the string:username in the Orders resource??

I guess one solution would be to do:

api.add_resources(Orders, '/api/v1/orders/') 

and send query parameters specifying the user i want to get the orders from, but I wanted to know if its possible to do something like the above example.


Solution

  • Well, i finally got it. Here's the solution

    Lets suppose we have a endpoint of users that can be looked by name, and the users have orders that can also be queried. orders query will be a generic thing, it would only need the corresponding query parameters, and will need to know on which user it will have to look for orders:

    from flask import Flask
    from flask_restful import Api
    
    
    app = Flask(__name__)
    app.config['DEBUG'] = True
    
    from views import *
    
    api = Api(app)
    api.add_resource(OrdersQuery, '/api/v1/user/<string:name>/orders/query/')
    

    And when defining the resources class:

    class OrdersQuery(Resource):
        def get(self, name):
            ## do something with name, like retrieving the user
            ## probably grab the orders and apply the query with the params from the url
            return jsonify({
                'result_list': [..something in here..]
            })
    

    As you can see, you are using the variable part of the url, the name of the user, for the query orders endpoint.