Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide Django rest framework Routers Api View Page

I am using DjangoRestFramework 3.3.2 for Routing in my django application. I have 6 different folders for 6 apps and 1 main project app. I have include all 6 apps urls into main url file. Following is my main url file.

from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^vpc/', include('vpc.urls')),
    url(r'^dss/', include('dss.urls')),
    url(r'^rds/', include('rds.urls')),
    url(r'^compute/', include('compute.urls')),
    url(r'^iam/', include('iam.urls')),
]

And this is my one of app url file.

from django.conf.urls import url
from rest_framework import routers
import views.instance_views as instance
import views.snapshot_views as snapshot

router = routers.SimpleRouter()
router.register(r'instance', instance.IntanceViewSet, base_name='instance')
router.register(r'snapshot', snapshot.SnapshotViewSet, base_name='snapshot')

urlpatterns = []

urlpatterns += router.urls

Now my problem is when I open urls in browser, I can see whole url hierarchy. Which is not required.Snapshot of Api root view

How do I hide these rendered views. I don't want to show any extra information

I was able to hide view using:

REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': (
        'rest_framework.renderers.JSONRenderer',
    )
}

But I am still getting all urls under 1 app.

{"instance":"http://127.0.0.1:8000/compute/instance/","keypair":"http://127.0.0.1:8000/compute/keypair/","volume":"http://127.0.0.1:8000/compute/volume/","image":"http://127.0.0.1:8000/compute/image/","snapshot":"http://127.0.0.1:8000/compute/snapshot/"}
like image 896
Anshum17 Avatar asked Feb 05 '23 21:02

Anshum17


2 Answers

In your urls.py change the default router to simple router.

router = routers.SimpleRouter()

You should also add the following snippet in your production settings file to only enable JSONRenderer for the API, This will completely disable the web browsable API.

REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': (
        'rest_framework.renderers.JSONRenderer',
    )
}
like image 179
Zed Avatar answered Feb 11 '23 10:02

Zed


Just to update on the answers given. You do need to specify the SimpleRouter() router, but often the DefaultRouter() router is useful for viewing and debugging whilst in development.

With that in mind, I would advise doing the simple following step:

if settings.DEBUG:
    router = DefaultRouter()
else:
    router = SimpleRouter()

Then as normal:

from myproject.users.api.viewsets import UserViewSet

router.register(r'users', UserViewSet)
like image 45
Micheal J. Roberts Avatar answered Feb 11 '23 10:02

Micheal J. Roberts