Add Base Url to Django Rest Swagger

6.7k views Asked by At

I can't find a way to add the BASE URL to the django rest swagger. I tried adding

SWAGGER_SETTINGS = {
    "base_path": 'localhost:62090/',
}

to settings.py. But its not working.

2

There are 2 answers

2
Sudaraka Jayathilaka On BEST ANSWER

I couldn't find a way to display the base url in the swagger ui, but I could add the base url like this in urls.py

schema_view = get_swagger_view(title='Pastebin API',url='/pastebin/')

This code adds the base url between the host and the url u specified.

0
spiderlama On

Essentially you need to set basePath on the OpenAPI JSON response. To do this with django_rest_swagger:

renderers.py:

from __future__ import absolute_import, division, print_function, unicode_literals

from django.core.urlresolvers import reverse
from rest_framework_swagger import renderers


class OpenAPIRenderer(renderers.OpenAPIRenderer):
    def get_customizations(self):
        data = super(OpenAPIRenderer, self).get_customizations()
        data['basePath'] = reverse('api-root')  # your base url here
        return data

views.py:

from rest_framework import exceptions
from rest_framework.permissions import AllowAny
from rest_framework.renderers import CoreJSONRenderer
from rest_framework.response import Response
from rest_framework.schemas import SchemaGenerator
from rest_framework.views import APIView
from rest_framework_swagger import renderers

from .renderers import OpenAPIRenderer


class SwaggerSchemaView(APIView):
    _ignore_model_permissions = True
    exclude_from_schema = True
    permission_classes = [AllowAny]
    renderer_classes = [
        CoreJSONRenderer,
        OpenAPIRenderer,  # your OpenAPIRenderer here
        renderers.SwaggerUIRenderer
    ]

    def get(self, request):
        generator = SchemaGenerator(
            title=title,
            url=url,
            patterns=patterns,
            urlconf=urlconf
        )
        schema = generator.get_schema(request=request)

        if not schema:
            raise exceptions.ValidationError(
                'The schema generator did not return a schema Document'
            )

        return Response(schema)

urls.py:

from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^$', views.SwaggerSchemaView.as_view(), name='api-root'),  # your swagger view here
]