8

We have a bunch of api's with different versions in urls.py, eg

  • api/v1
  • api/v2
  • api/v3

. We want to implement swagger with drf-spectacular, but we only want to expose api/v3 endpoints.

Is there a way to do this? I cannot make sense of the documentation.

Thanks

Gareth
  • 89
  • 1
  • 3
  • there seems to be a way in drf-yasg with get_schema_view "patterns". I don't think this is translated to drf-spectacular. – Gareth Aug 26 '21 at 17:54

4 Answers4

15

This works for me:

def preprocessing_filter_spec(endpoints):
    filtered = []
    for (path, path_regex, method, callback) in endpoints:
        # Remove all but DRF API endpoints
        if path.startswith("/api/"):
            filtered.append((path, path_regex, method, callback))
    return filtered

In settings:

"PREPROCESSING_HOOKS": ["common.openapi.preprocessing_filter_spec"],
Chris
  • 5,664
  • 6
  • 44
  • 55
3

You could also exclude it with the following:


    from drf_spectacular.utils import extend_schema
    ...
    
    @extend_schema(
        exclude=True
    )
    @api_view(['GET'])
    def my_view(request):
        # your code here

Or you could exclude a whole viewset:


    @extend_schema_view(
        list=extend_schema(exclude=True),
        retrieve=extend_schema(exclude=True),
        create=extend_schema(exclude=True),
        update=extend_schema(exclude=True),
        partial_update=extend_schema(exclude=True),
        destroy=extend_schema(exclude=True)
    )
jfunk
  • 7,176
  • 4
  • 37
  • 38
0

Worked it out. Copied the custom preprocessing hook function, changed the pass statement to filter what I did not require in the endpoints, then mapped the location of the file and function in my spectacular settings for preprocessed hooks.

Gareth
  • 89
  • 1
  • 3
0

In Detail:

Create a file in same directory where setting.py is. Let's say file name is excluded_path.py

1- Add to excluded_path.py:
Here's the schema is path we don't want to show in output of docs.

def custom_preprocessing_hook(endpoints):
   filtered = []
   for (path, path_regex, method, callback) in endpoints:
       if "schema" not in path:
           filtered.append((path, path_regex, method, callback))
   return filtered

2- settings.py

SPECTACULAR_SETTINGS = {
   'PREPROCESSING_HOOKS': ["djapi.excluded_path.custom_preprocessing_hook"]
}
Nerdy Ayubi
  • 70
  • 1
  • 7