django swagger
Install Django and Django REST Framework:
bash pip install django djangorestframework
Create a new Django project:
bash django-admin startproject myproject
Create a new Django app:
bash cd myproject python manage.py startapp myapp
Install
drf-yasg
for Swagger support:bash pip install drf-yasg
Update
INSTALLED_APPS
insettings.py
:python INSTALLED_APPS = [ # ... 'rest_framework', 'drf_yasg', 'myapp', ]
Configure
urls.py
in the app to include the DRF views: ```python from django.contrib import admin from django.urls import path, include from rest_framework import permissions from drf_yasg.views import get_schema_view from drf_yasg import openapi
schema_view = get_schema_view( openapi.Info( title="My API", default_version='v1', description="Description of my API", terms_of_service="https://www.myapp.com/terms/", contact=openapi.Contact(email="[email protected]"), license=openapi.License(name="Your License"), ), public=True, permission_classes=(permissions.AllowAny,), )
urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('myapp.urls')), path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), ] ```
- Define API endpoints in
myapp/views.py
: ```python from rest_framework.decorators import APIView from rest_framework.response import Response from rest_framework import status
class MyAPIView(APIView): def get(self, request): # Your implementation here return Response({"message": "Hello, World!"}, status=status.HTTP_200_OK) ```
- Configure
myapp/urls.py
to include the API views: ```python from django.urls import path from .views import MyAPIView
urlpatterns = [ path('myapi/', MyAPIView.as_view(), name='my-api'), ] ```
Run migrations and start the development server:
bash python manage.py makemigrations python manage.py migrate python manage.py runserver
Access Swagger documentation at http://localhost:8000/swagger/ to interact with and explore your API.