10

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.

Sebastian
  • 1,243
  • 1
  • 18
  • 34

1 Answers1

10

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.

Sebastian
  • 1,243
  • 1
  • 18
  • 34
  • How could I do something like /api/v1/user//orders//query/ with flask_restful? would appreciate if you could point me in the right direction... – Rotkiv Dec 01 '19 at 22:04
  • 1
    you would do the same, only that you will have 2 parameters in the url string and the get method. But if you are already sending the order id, then why would you send a query? anyway, if that's what you need you can do it the same way as above adding the new parameter. – Sebastian Dec 02 '19 at 18:38