1. Définitions des termes utilisés
- API (Application Programming Interface) : Interface qui permet à différentes applications de communiquer entre elles. Exemple : Votre frontend React communique avec votre backend Django via une API
- REST (Representational State Transfer) : Architecture standard pour créer des APIs web Utilise les verbes HTTP (GET, POST, PUT, DELETE) Sans état (stateless) et structuré
- DRF (Django REST Framework) : Bibliothèque Django puissante pour créer des APIs REST. Ajoute des fonctionnalités spécifiques aux APIs
- Serializer : Convertit les données Django (modèles) en JSON/XML. Valide les données entrantes. Similaire aux forms Django mais pour les APIs
2. Installation & Configuration des outils nécessaires
2.1 Installation
1 |
pip install djangorestframework |
2.1 Réglage : Ajouter dans settings.py
Afin de faire fonctionner le framework 'rest_framework', nous devons l'ajouter à la liste des applications installées au niveau du fichier settings.py:
1 2 3 4 |
INSTALLED_APPS = [ # ... 'rest_framework', ] |
3. A propos du package 'rest_framework'
'rest_framework' est le nom du package Python qui contient Django REST Framework (DRF).
Qu'est-ce que c'est ?
- Package officiel (rest_framework) : Le nom exact à installer via pip et utilisé dans l'écosystème Python
- Collection de modules : Ensemble d'outils spécialisés pour les APIs. 'rest_framework' n'est pas un outil unique mais une boîte à outils complète formée de plusieurs modules. Chaque module a un rôle spécifique dans la création d'APIs.
- Extension de Django : S'intègre parfaitement avec l'écosystème Django existant. DRF étend Django, ne le remplace pas, mais il utilise les composants Django existants tout en respectant les patterns et conventions de Django.
- Structure du package :
12345678rest_framework.views # Classes pour créer des vues APIrest_framework.serializers # Classes pour la sérialisationrest_framework.response # Réponses HTTP typéesrest_framework.status # Codes HTTP standardsrest_framework.generics # Vues génériques préfaitesrest_framework.decorators # Décorateurs pour les APIsrest_framework.permissions # Système de permissionsrest_framework.authentication # Méthodes d'authentification - Importance dans le code :
12345# Tous ces imports viennent du package rest_frameworkfrom rest_framework import generics # ← vient de rest_frameworkfrom rest_framework import serializers # ← vient de rest_frameworkfrom rest_framework.views import APIView # ← vient de rest_frameworkfrom rest_framework.response import Response # ← vient de rest_framework
4. Exemple concret d'usage de 'rest_framework'
Nous allons voir dans un exemple simple de plateforme e-commerce, comment utiliser le package 'rest_framework':
4.1 Modèle (models.py)
1 2 3 4 5 6 7 8 9 |
from django.db import models class Produit(models.Model): nom = models.CharField(max_length=100) prix = models.DecimalField(max_digits=10, decimal_places=2) en_stock = models.BooleanField(default=True) def __str__(self): return self.nom |
4.2 Serializer (serializers.py)
1 2 3 4 5 6 7 |
from rest_framework import serializers from .models import Produit class ProduitSerializer(serializers.ModelSerializer): class Meta: model = Produit fields = ['id', 'nom', 'prix', 'en_stock'] # Champs à inclure dans l'API |
4.3 View (views.py) - Méthode la plus simple
1 2 3 4 5 6 7 8 9 10 11 |
from rest_framework import generics from .models import Produit from .serializers import ProduitSerializer class ProduitListCreate(generics.ListCreateAPIView): queryset = Produit.objects.all() serializer_class = ProduitSerializer class ProduitDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Produit.objects.all() serializer_class = ProduitSerializer |
4.4 URLs (urls.py)
1 2 3 4 5 6 7 |
from django.urls import path from . import views urlpatterns = [ path('produits/', views.ProduitListCreate.as_view()), path('produits//', views.ProduitDetail.as_view()), ] |
5. Utilisation de l'API
Nous montrons dans ce paragraphe, comment créer, lister et récupérer des produits
5.1 Créer un produit (POST)
1 2 3 |
curl -X POST http://localhost:8000/api/produits/ \ -H "Content-Type: application/json" \ -d '{"nom": "Laptop", "prix": "999.99", "en_stock": true}' |
5.2 Lister tous les produits (GET)
1 |
curl http://localhost:8000/api/produits/ |
5.3 Récupérer un produit spécifique (GET)
1 |
curl http://localhost:8000/api/produits/1/ |
5.4 Mise à jour (PUT)
1 2 3 |
curl -X PUT http://localhost:8000/api/produits/1/ \ -H "Content-Type: application/json" \ -d '{"nom": "Laptop Gaming", "prix": "1299.99", "en_stock": true}' |
5.5 Suppression (DELETE)
1 |
curl -X DELETE http://localhost:8000/api/produits/1/ |
6. Version avec APIView (plus de contrôle)
6.1 Pourquoi APIView donne plus de contrôle?
Avec generics (ListCreateAPIView, RetrieveUpdateDestroyAPIView):
Tout est pré-défini : Les méthodes HTTP sont gérées automatiquement
- Peu de personnalisation possible
- Rapide mais rigide
Avec APIView:
- Vous écrivez chaque méthode manuellement
- Contrôle total sur la logique métier
Personnalisation avancée possible
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status class ProduitList(APIView): def get(self, request): produits = Produit.objects.all() serializer = ProduitSerializer(produits, many=True) return Response(serializer.data) def post(self, request): serializer = ProduitSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) |
Configuration DRF (settings.py)
1 2 3 4 5 6 7 |
REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 10, 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticatedOrReadOnly', ] } |
7. Conclusion : Points Clés à Retenir
Nous devons finalement retenir le nom et la fonction de chaque classe du framework 'rest_framework'
- Serializer : Conversion données Django ↔ JSON
- APIView : Vue spécialisée pour les APIs
- Generics : Vues préfaites (CRUD automatique)
- URLs : Point d'entrée de l'API
- HTTP Methods : GET(lire), POST(créer), PUT(modifier), DELETE(supprimer)
Younes Derfoufi
CRMEF OUJDA