4

I use Django 2.1 and DRF and a planning a quite larger application with many plugged-in apps. I'd like to have ONE /api URL for the DRF as endpoint, but allow each app to have a special model exposed over the REST endpoint, e.g.:

In the main urls.py:

router = routers.DefaultRouter()
router.register(r'users', UserViewSet)

urlpatterns = [
    # ...
    path('api/', include(router.urls)),
    # ...
]

and in foo_app/urls.py:

router = routers.DefaultRouter()
router.register(r'foomodel', FooModelViewSet)

Now, /api/foomodel produces a 404 Error. The foo_model/urls.py gets imported (a print statement there is printed at Django start), and all the other foo_model.urlpattern[path...] are recognized and work fine.

How can I define custom api model endpoints for a central api REST endpoint? I didn't find anything in the documentation.

Thanks in advance.

2 Answers 2

7

I simply achieved this by extending the router registries.

root urls.py

from ad.urls import router as ad_router

main_router = routers.DefaultRouter()
main_router.registry.extend(ad_router.registry)

ad.urls.py

from .api.urls import router as api_router

router = routers.DefaultRouter()
router.registry.extend(api_router.registry)

ad.api.urls.py

router = routers.DefaultRouter()
router.register(r'ad', AdViewSet)
Sign up to request clarification or add additional context in comments.

3 Comments

whow, seems nice, I'll have a look at this ASAP.
This is at least a bit more in the direction I want. I can't use main_router.registry.extend(ad_router.registry), as main_router doesn't know about ad_router (or other plugins). But I can maybe solve that using the GDAPS plugin system. Thanks.
2

In your main urls.py you would do something like this. (This is for Django 1.8)

urlpatterns += patterns('',
url(r'^api/', include(patterns('',
    url(r'^foo_app/', include('foo_app.urls')),
    url(r'^bar_app/', include('bar_app.urls')),
    url(r'^test_app/', include('test_app.urls')),
))))

this allows you to access all your endpoints this way

localhost:8000/api/foo_app/<foo_app_endpoint>
localhost:8000/api/bar_app/<bar_app_endpoint>
localhost:8000/api/bar_app/<test_app_endpoint>

1 Comment

Ok. The good old include thing. But that's not pluggable. I want my app to bring it's URL pattern along, and not add all plugins manually in the main urls.py file. I wrote my own plugin system (GDAPS, alpha,, on pypi) which could deal with that. But I thought that with the "router" of the rest_framework this could be done easier? Do I really haveto use the "pattern" adding additionally? What is the router then for?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.