[Fixed]-Custom Grouping on OpenAPI endpoints with Django Rest Framework

30๐Ÿ‘

โœ…

you are making it harder than it needs to be. In the global settings you can specify a common prefix regex that strips the unwanted parts. that would clean up both operation_id and tags for you. In your case that would probably be:

SPECTACULAR_SETTINGS = {
    'SCHEMA_PATH_PREFIX': r'/api/v[0-9]',
}

that should result in tags: home, jwt-auth, swagger.json, swagger.yaml

the tags on @extend_schema is merely a convenience to deviate from the default where needed. it would be cumbersome to do this for every operation. see the settings for more details:

https://drf-spectacular.readthedocs.io/en/latest/settings.html

for even more elaborate tagging you can always subclass AutoSchema and override get_tags(self) to your liking. cheers!

๐Ÿ‘คInsa

12๐Ÿ‘

Turns out that you can control this by changing the tags in a view, as per OpenAPI specification: https://swagger.io/docs/specification/grouping-operations-with-tags/

So, with drf-spectacular, you can use the extend_schema decorator to achieve this, e.g.:

from drf_spectacular.utils import extend_schema

class CustomTokenObtainPairView(TokenObtainPairView):
    """
    Takes a set of user credentials and returns an access and refresh JSON web
    token pair to prove the authentication of those credentials.
    """
    @extend_schema(
        operation_id="jwt_obtain",
        ....
        tags=["aTestTag"]
    )
    def post(self, request, *args, **kwargs):
        # whatever

So you have to use this decorator to extend the schema in each view that you want to put into a custom group.

๐Ÿ‘คbabis21

Leave a comment