API REST
Django REST Framework (DRF)
-
Installation
Fenêtre de terminal pip install djangorestframework -
Configuration
task_manager/settings.py ...INSTALLED_APPS = ['django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles','todolist','rest_framework',]... -
Désactiver CSRF
task_manager/settings.py ...# Désactiver CSRF pour les APICSRF_TRUSTED_ORIGINS = ['http://127.0.0.1:8000']... -
Serializers
Les serializers transforment les instances des modèles en JSON (et inversemenent).
todolist/serializers.py from rest_framework import serializersfrom .models import Taskclass TaskSerializer(serializers.ModelSerializer):class Meta:model = Taskfields = ['id', 'title', 'description', 'completed', 'due_date', 'assigned_to'] -
Views
Création des vues basées sur Django REST Framework pour gérer les opérations CRUD des tâches.
todolist/views.python from rest_framework import viewsetsfrom .models import Taskfrom .serializers import TaskSerializerclass TaskViewSet(viewsets.ModelViewSet):queryset = Task.objects.all().order_by('due_date')serializer_class = TaskSerializer -
Routes
Création des routeurs pour accéder à l’API en utilisant un routeur fourni par Django REST Framework.
task_manager/urls.py from django.contrib import adminfrom django.urls import pathfrom django.urls import path, includefrom todolist import viewsfrom rest_framework import routersrouter = routers.DefaultRouter()router.register(r'tasks', views.TaskViewSet)urlpatterns = [path('admin/', admin.site.urls),path('api/', include(router.urls)),] -
Pagination
task_manager/settings.py ...REST_FRAMEWORK = {'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination','PAGE_SIZE': 10}... -
Filtres
todolist/views.py from rest_framework import viewsetsfrom .models import Taskfrom .serializers import TaskSerializerfrom django_filters.rest_framework import DjangoFilterBackendclass TaskViewSet(viewsets.ModelViewSet):queryset = Task.objects.all().order_by('due_date')serializer_class = TaskSerializerfilter_backends = [DjangoFilterBackend]filterset_fields = ['completed', 'assigned_to']
Swagger UI
-
Installation
Fenêtre de terminal pip install drf-yasg -
Intégration d’OpenApi
Création d’un fichier
swagger.py
, pour configurer la documentation d’OpenApi.from rest_framework import permissionsfrom drf_yasg.views import get_schema_viewfrom drf_yasg import openapischema_view = get_schema_view(openapi.Info(title="Mon API de todolist",default_version='v1',description="Test description",terms_of_service="https://www.google.com/policies/terms/",contact=openapi.Contact(email="contact@kevindb.dev"),license=openapi.License(name="BSD License"),),public=True,permission_classes=(permissions.AllowAny,),) -
Route
task_manager/urls.py from django.contrib import adminfrom django.urls import path, includefrom todolist import viewsfrom rest_framework import routersrouter = routers.DefaultRouter()router.register(r'tasks', views.TaskViewSet)urlpatterns = [path('admin/', admin.site.urls),path('tasks/', views.task_list, name='task_list'),path('api/', include(router.urls)),path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),] -
Configuration
Modification du fichier
task_manager/settings.py
, ajout de la sectionSWAGGER_SETTINGS
.task_manager/settings.py ...SWAGGER_SETTINGS = {'SECURITY_DEFINITIONS': {'Bearer': {'type': 'apiKey','name': 'Authorization','in': 'header'}},'USE_SESSION_AUTH': False,}...
Sécurisation par Token indépendant
-
Modèle
todolist/models.py ...class APIToken(models.Model):token = models.CharField(max_length=255, unique=True)description = models.CharField(max_length=255, blank=True, null=True) # Facultatif, pour une description du tokencreated_at = models.DateTimeField(auto_now_add=True)def __str__(self):return self.token -
Authentification personnalisée
todolist/authentification.py from rest_framework.authentication import BaseAuthenticationfrom rest_framework.exceptions import AuthenticationFailedfrom .models import APITokenclass StaticTokenAuthentication(BaseAuthentication):def authenticate(self, request):auth_header = request.headers.get('Authorization')if not auth_header:return None # Pas de header Authorizationif not auth_header.startswith('Bearer '):raise AuthenticationFailed('Le token doit commencer par "Bearer"')token = auth_header.split(' ')[1] # Extraire le token après 'Bearer'try:APIToken.objects.get(token=token)except APIToken.DoesNotExist:raise AuthenticationFailed('Token invalide ou manquant')return (None, None) # Autorise la requête -
Permisssion personnalisée
from rest_framework.permissions import BasePermissionclass HasValidAPIToken(BasePermission):"""Autorise uniquement les requêtes qui ont passé l'authentification par token statique."""def has_permission(self, request, view):# Si la requête a un token valide, la permission est accordéeif request.auth is None and request.user is None:return Truereturn False
CORS
-
Installation
Fenêtre de terminal pip install django-cors-headers