Reputation: 106
Currently, the project I'm working on has an API like the following:
api/
visitors/ # Endpoint returning list of visitors
visitor-rates/ # Endpoint returning visitors per time
gift-shop-orders/ # Endpoint returning purchases at the gift shop
order-rates/ # Endpoint returning purchases per time
What I'd like to do is group the visitor and gift shop endpoints under their own sub-heading. For example:
api/
visits/
visitors/
rates/
gift-shop/
orders/
rates/
Note that visits
and gift-shop
only have the job of listing out the URLs that are available under the respective subheading. So, a GET request to /api/visits
should return:
{
"visitors": "/api/visits/visitors",
"rates": "/api/visits/rates"
}
In other words, I'd like /api/visits/
and /api/gift-shop/
to have the same behavior as the default router view used by Django for displaying the endpoints available in the root of the API (/api/
).
I've tried simply nesting just the URLs together. So, suppose I've defined routers for the visitor endpoints and shop endpoints. I've tried:
api_patterns = [
url(r'^visits/', include(visitor_router.urls)),
url(r'^gift-shop/', include(shop_router.urls)),
]
urlpatterns = [
url(r'^api/', include(api_patterns)),
]
This makes it so that requests to /api/visits/
and /api/gift-shop/
respond correctly. However, if I go to /api/
, no links to /api/visits
or /api/gift-shop
are given.
This leads me to believe that I need to nest the routers themselves, not just the URLs. I haven't seen any documentation on doing this, though, and my attempts at coming up with a custom solution have only led to other issues. Does anyone know if there is a simple, standard way to do this that I am missing?
tl;dr: How do I nest Django routers?
Upvotes: 1
Views: 124
Reputation: 8506
The short answer is you don't. If you're using ViewSets as a way to simplify your views, you need to stick to the rules of ViewSets, and if you want to have nested routes, you can do it with the @detail_route
and @list_route
decorators, but they don't express your resources as the rest of the framework does, and it's a manual labor.
The alternative, is using a third-party package called drf-nested-routers, which is really well done and can definitely do what you're expecting.
Upvotes: 1