Setup the Project for Django REST Framework¶
Install Django REST Framework and implement Swagger interface for the API.
Install Django REST Framework¶
Modify requirements.txt adding djangorestframework and drf-yasg as dependencies:
# ...
djangorestframework
# ...
We are using drf-yasg to generate Swagger interface for our API.
Run pip to reflect the changes:
$ pip install -r requirements.txt
Create Swagger interface for Our API¶
We are using drf-yasg as Swagger interface generator so if not already installed, you need to install it:
$ pip install drf-yasg
...
drf-yasg is a Django application so you need to register it in the project’s settings.py:
# ...
INSTALLED_APPS = [
# ...
# 3rd party apps
'drf_yasg',
# Local apps
# ...
]
# ...
We need also to do a litle work to define a view for our Swagger interface and register it the /docs/ url for it.
1from drf_yasg.views import get_schema_view
2from drf_yasg import openapi
3from rest_framework import permissions
4
5schema_view = get_schema_view(
6 openapi.Info(
7 title="BEL",
8 default_version='v1',
9 description="Brith E-Learning (BEL) API",
10 terms_of_service="https://www.bel.local/bel/terms/",
11 contact=openapi.Contact(email="contact@bel.local"),
12 license=openapi.License(name="BSD License"),
13 ),
14 public=True,
15 permission_classes=(permissions.AllowAny,),
16)
1from django.contrib import admin
2from django.urls import path
3from .views import schema_view
4
5
6urlpatterns = [
7 path('docs/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
8 path('admin/', admin.site.urls),
9]
Preview Our API Swagger interface¶
Now you can run a development server:
$ python elearn/manage.py runserver
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
September 09, 2023 - 17:22:26
Django version 4.2, using settings 'elearn.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
And navigate to http://127.0.0.1:8000/docs/ to see the brand new beautiful Swagger interface for our API. It has no APIs defined as we haven’t created any URLs yet.