All guides
IntermediateSelf-pacedFree GuideSection 41/95

APIs REST — Principes fondamentaux

Practise development foundations: programming, web, APIs, data and AI tools. Work through sections and exercises to build your first projects.

The full lessons for this course are currently available in French. Use the section menu to navigate the French course.

💡

Free content, available without an account. Tools and models change: use the current model guide to check their versions. Models and sources

Section 11.3.2 : APIs REST — Principes fondamentaux

🎯 Objectif pédagogique

Comprendre en profondeur le fonctionnement des APIs REST : méthodes HTTP, codes de statut, headers, et structure des requêtes/réponses. Vous serez capable de lire une documentation d'API et de comprendre chaque aspect d'un échange client-serveur.


L'API est le contrat universel du web

En Semaine 1, Marc a fait son premier appel API. Maintenant il faut comprendre en profondeur comment ça fonctionne. Une API REST (Representational State Transfer) est un contrat entre deux logiciels : "tu m'envoies X, je te retourne Y".

Anatomie d'une requête HTTP

GET /api/v1/applications?status=interview&limit=10 HTTP/1.1
Host: api.jobtracker.com
Authorization: Bearer eyJhbGciOiJIUzI1NiJ9...
Content-Type: application/json
Accept: application/json

───── DÉCOMPOSITION ─────
GET                    → Méthode HTTP (action)
/api/v1/applications   → Endpoint (ressource)
?status=interview      → Query parameters (filtres)
Host: ...              → Headers (métadonnées)
Authorization: ...     → Authentification
Content-Type: ...      → Format du corps de la requête

Les méthodes HTTP = CRUD

MéthodeActionSQL équivalentIdempotentCorps
GETLireSELECT✅ Oui❌ Non
POSTCréerINSERT❌ Non✅ Oui
PUTRemplacerUPDATE (total)✅ Oui✅ Oui
PATCHModifier partiellementUPDATE (partiel)✅ Oui✅ Oui
DELETESupprimerDELETE✅ Oui❌ Non

Codes de statut HTTP

# Les codes à connaître par coeur

# ✅ Succès (2xx)
# 200 OK          → Tout va bien
# 201 Created     → Ressource créée (après POST)
# 204 No Content  → Succès, pas de corps (après DELETE)

# ⚠️ Redirection (3xx)
# 301 Moved       → URL changée définitivement
# 304 Not Modified → Pas de changement (cache valide)

# ❌ Erreur client (4xx)
# 400 Bad Request  → Requête mal formée
# 401 Unauthorized → Pas authentifié
# 403 Forbidden    → Authentifié mais pas autorisé
# 404 Not Found    → Ressource inexistante
# 429 Too Many     → Rate limit dépassé

# 💥 Erreur serveur (5xx)
# 500 Internal     → Bug côté serveur
# 502 Bad Gateway  → Proxy/load balancer fail
# 503 Unavailable  → Serveur surchargé/maintenance

Structure d'une API REST bien conçue

# Convention d'URL : /ressource (pluriel)
GET    /api/v1/applications         → Liste des candidatures
GET    /api/v1/applications/42      → Candidature #42
POST   /api/v1/applications         → Créer une candidature
PUT    /api/v1/applications/42      → Remplacer la candidature #42
PATCH  /api/v1/applications/42      → Modifier partiellement #42
DELETE /api/v1/applications/42      → Supprimer #42

# Relations
GET    /api/v1/users/1/applications → Candidatures de l'user 1
POST   /api/v1/applications/42/notes → Ajouter une note à la candidature 42

# Filtres, tri, pagination
GET    /api/v1/applications?status=interview&sort=-date&page=2&limit=20

Headers importants

HeaderRôleExemple
Content-TypeFormat du bodyapplication/json
AuthorizationAuthentificationBearer <token>
AcceptFormat souhaité en retourapplication/json
Cache-ControlPolitique de cachemax-age=3600
Rate-Limit-RemainingRequêtes restantes47

REST vs GraphQL vs gRPC

REST est le standard dominant (>80% des APIs web). GraphQL (Facebook) permet de demander exactement les champs voulus — utile pour les apps mobiles. gRPC (Google) utilise du binaire — ultra-rapide pour les microservices. Pour 95% des cas, REST suffit.

🏋️ Exercice pratique (15 minutes)

Sans coder, lisez cette documentation d'API et répondez :

API: Open Meteo (météo gratuite, pas de clé API)
Base URL: https://api.open-meteo.com/v1

Endpoint: /forecast
Method: GET
Parameters:
  - latitude (required): float
  - longitude (required): float
  - current_weather (optional): boolean
  - hourly (optional): string (temperature_2m, rain, etc.)
  - daily (optional): string
  - timezone (optional): string

Example:
GET /v1/forecast?latitude=48.86&longitude=2.35&current_weather=true
  1. →Quelle URL complète pour la météo actuelle de Paris ?
  2. →Comment ajouter la température horaire ?
  3. →Quelle méthode HTTP utiliser ?
  4. →Un body est-il nécessaire ?
Quick Check

Quelle est la différence entre une erreur 401 et une erreur 403 ?

Quick Check

Pourquoi une API REST utilise-t-elle des noms de ressources au pluriel (/users, /applications) ?

Learn AI, from prompts to agents

15 free guidesQuizzes, diagrams and workshopsNo account needed

Your progress

Progress is self-reported and stored in your browser. The final completion record is not a qualification or an independent assessment.

View progress and completion record

Learn AI, from prompts to agents

15 free guidesQuizzes, diagrams and workshopsNo account needed

One practical AI workflow in your inbox

Methods, resources and new exercises. Free, unsubscribe at any time.