Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add custom OpenAPISchemaGenerator to fix Swagger endpoint URLs #144

Merged
merged 1 commit into from
Jun 12, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions api/urls.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,44 @@
"""URL configuration for the API application."""
from typing import Any, Dict, Tuple
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

❤️ thank you for adding typing here


from django.conf.urls import include, url
from django.urls import path
from drf_yasg import openapi
from drf_yasg.generators import OpenAPISchemaGenerator
from drf_yasg.views import get_schema_view
from rest_framework import permissions, routers

from api.views import misc, slack, source, submission, transcription, volunteer


class CustomOpenAPISchemaGenerator(OpenAPISchemaGenerator):
"""Custom schema generator required for Swagger to point the requests to the correct URL.

See https://github.com/axnsan12/drf-yasg/issues/146#issuecomment-478757552.
"""

def get_schema(
self, *args: Tuple[Any, ...], **kwargs: Dict[str, Any]
) -> openapi.Swagger:
"""Generate a :class:`.Swagger` object representing the API schema.

:param request: the request used for filtering accessible endpoints and finding
the spec URI
:type request: rest_framework.request.Request or None
:param bool public: if True, all endpoints are included regardless of access
through `request`
:param args: the args for the schema
:param kwargs: the kwargs for the schema

:return: the generated Swagger specification
:rtype: openapi.Swagger
"""
schema = super().get_schema(*args, **kwargs)
# This makes sure that Swagger points to the /api/ endpoint.
schema.basePath = "/api"
return schema


schema_view = get_schema_view(
openapi.Info(
title="Grafeas Group - Transcriptions API",
Expand All @@ -19,6 +51,7 @@
public=True,
permission_classes=(permissions.AllowAny,),
urlconf="api.urls",
generator_class=CustomOpenAPISchemaGenerator,
)

# automatically build URLs, as recommended by django-rest-framework docs
Expand Down