Fluorescent Nested Resources

Im refactoring my leisure api server to use Flask-RESTful, and im that has some doubts in some special cases when I need to get a list of resources belonging to another. Something like that:

/api/v1/users/john/orders 

How would you develop this? Because, if I have a resource called "Orders", I need to know from which user I should receive orders. But how can I tell the resource about the user? I do not see any __ init __ method where I can specify parameters for resources.

I thought about doing something similar when registering the Orders resource:

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

But how can I access the line : username in the Orders resource?

I think one solution would be to make:

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

and send the request parameters, indicating the user from whom I want to receive orders, but I wanted to know if it is possible to do something similar to the above example.

+5
source share
1 answer

Well, finally, I get it. Here is the solution

Suppose we have an endpoint of users that can be viewed by name, and users have orders that can also be requested. the request for orders will be general, it will only need the appropriate request parameters and should know which user it will search 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 a resource 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 username, for the endpoint of order requests.

+5
source

Source: https://habr.com/ru/post/1201515/


All Articles