Django drf-spectacular - Can you exclude specific paths?
Asked Answered
A

4

11

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

Aeniah answered 26/8, 2021 at 17:34 Comment(1)
there seems to be a way in drf-yasg with get_schema_view "patterns". I don't think this is translated to drf-spectacular.Aeniah
A
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.

Aeniah answered 27/8, 2021 at 18:45 Comment(0)
R
18

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"],
Roid answered 10/11, 2021 at 12:3 Comment(0)
F
12

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)
    )
Fanjet answered 31/5, 2023 at 14:44 Comment(0)
C
1

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"]
}
Coachwork answered 26/2, 2023 at 15:33 Comment(0)
A
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.

Aeniah answered 27/8, 2021 at 18:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.