Exclude URLs from Django REST Swagger
Asked Answered
S

7

19

I have a few URLs that I want to exclude from my REST API documentation. I'm using Django REST Swagger and the only documentation I can find (https://github.com/marcgibbons/django-rest-swagger) doesn't really tell me much. There is the "exclude_namespaces" part of SWAGGER_SETTINGS in settings.py, but there is no real explanation or example of how to use this.

Simply put, I want to exclude any URLs from the docs that start with the following:

/api/jobs/status/
/api/jobs/parameters/

How could I go about doing this?

Thanks in advance for any help offered :P

Seals answered 24/4, 2014 at 8:28 Comment(1)
I have a somewhat related but a more fine-grained question on excluding specific HTTP methods for specific endpoints: #52813753Chaing
P
19

the namespaces to exclude are the one defined in your urls.py.

So for example, in your case:

urls.py:

internal_apis = patterns('',
                     url(r'^/api/jobs/status/',...),
                     url(r'^/api/jobs/parameters/',...),
                     )

urlpatterns = urlpatterns + patterns('',
              url(r'^', include(internal_apis, namespace="internal_apis")),
              ...
              )

and in your settings.py:

SWAGGER_SETTINGS = {
    "exclude_namespaces": ["internal_apis"],    #  List URL namespaces to ignore
}

This is well described in there

Premillennial answered 24/4, 2014 at 8:54 Comment(1)
This is no longer works in the latest version of djangoDysprosium
L
19

For all of those who found the above answer not helpful: I guess that "exclude_namespaces" doesn't work anymore in new versions of django swagger. I had almost the same problem (I didnt't want to show my internal apis in documentation) and the above solution didn't work for me. I've been searching for like an hour for a solution and finally found something helpful.

There are some attributes that you can pass to SchemaGenerator. One of them is urlconf. You can set it to be "yourproject.api.urls" and it will get only urls defined there! Of course, you have to make sure that all the urls that you want to exclude from your api documentation are not included there.

I hope that at least one person found my answer helpful ;).

A problem comes when you want to have many urls.py included in your api documentation. I don't know what should be done then. If anyone comes up with an answer to this new problem - feel free to comment my answer. thanks!

Loosetongued answered 16/8, 2016 at 10:6 Comment(1)
You can also disable a specific view by adding schema = None to its attributes.Florella
D
8

With new version of django swagger, we don't need to create view to exclude some urls. Below code will disable test2 url.

from rest_framework_swagger.views import get_swagger_view
urlpatterns1 = [
    url(r'^', include(router.urls)),
    url(r'^test/', include('test.urls')),
    url(r'^test1/', Test2.as_view()),
]

schema_view = get_swagger_view(title='API Documentation', patterns=urlpatterns1)

urlpatterns = urlpatterns1 + [
    url(r'^docs/', schema_view),
    url(r'^test2/', Test2.as_view()),
]
Dreddy answered 6/7, 2017 at 9:46 Comment(0)
K
6

Ola's answer is correct. exclude_namespaces is no longer supported.

For finer control of the documentation, create your own schema view by using a function-based or class-based view. This can be useful if you want to produce documentation for specific URL patterns, or URL confs.

In your views.py, you can do the following:

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.schemas import SchemaGenerator
from rest_framework_swagger import renderers

class SwaggerSchemaView(APIView):
    renderer_classes = [
        renderers.OpenAPIRenderer,
        renderers.SwaggerUIRenderer
    ]

    def get(self, request):
        generator = SchemaGenerator(title='Your API Documentation', urlconf='your_app.urls')
        schema = generator.get_schema(request=request)

    return Response(schema)

The above will only render documentation for the URLs that are specified in the urlconf argument of the SchemaGenerator. Also, don't forget to set up your urls.py as well:

from django.conf.urls import url
from views import SwaggerSchemaView

urlpatterns = [
    url(r'^api/v1/docs/$', SwaggerSchemaView.as_view(), name='docs'),
]
Katzir answered 9/1, 2017 at 17:8 Comment(4)
This answer looks as if it might well address I problem I have, but I'm not sure what is meant by the urlconf='your_app.urls' - would you mind expanding on that, please?Objection
@Objection it is the path to the urls.py file that corresponds to whatever URLs you want to generate the Swagger Schema View for. Does that help?Katzir
Thanks. All the API URLs are in a main urls.py file but I only need some of them to be displayed in the Swagger documentation. If Django can handle two files then I could presumably put those which are actually to be documented in a separate file, leaving the private ones in the main URL file.Objection
That's pretty much exactly what I did, except I created a new urls.py file for the private ones.Katzir
P
4

For the newest version of drf-swagger you can defile url patterns in the schema generator.

For example: url_patterns = ( url(r'^api/v1/', include(router.urls, namespace='api')), ) generator = schemas.SchemaGenerator(title='Core API', patterns=url_patterns)

Payson answered 22/8, 2016 at 8:37 Comment(0)
B
3

A more flexible solution would be:

from django.contrib import admin
from django.urls import include, path
from rest_framework_swagger.views import get_swagger_view
urlpatterns = [
    path('admin/', admin.site.urls),
    path('users/', include('user.urls', namespace="user")),
    path('locations/', include('location.urls')),
    path('departments/', include('department.urls', namespace="department")),
    path('my_secret_api/', include('secret.urls', namespace="secret_api")),
]

to_exclude = ['secret_api',] # some more namespaces here
swagger_urls = [item for item in urlpatterns if hasattr(item,"namespace") and item.namespace not in to_exclude]
schema_view = get_swagger_view(title='Highky', patterns=swagger_urls)
urlpatterns += [
        path('api/docs/', schema_view),
]

urlpatterns will have all five paths, but swagger_urls will have four paths excluding secret_api.

All of your URLs and includes will continue to work as they were, except we are now passing our modified urlpatterns that we want to show in the Swagger docs. The checks will also cover the include where you don't specify a namespace (like in our case, where the namespace is not defined in the location).

Braynard answered 2/6, 2020 at 18:59 Comment(0)
C
1

views.py

any view class

class ...ViewSet(viewsets.ModelViewSet):
    queryset = ....objects.all().order_by('-id')
    serializer_class = ...Serializer
    http_method_names = ['get', 'post', 'patch', 'delete'] # add or exclude

any function-based view

@api_view(['get']) # target field
def function(request):
    ...
    return Response(...)
Close answered 15/11, 2021 at 8:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.