12
Fetch & API
Requêtes HTTP & REST API
L'API Fetch est le standard moderne pour effectuer des requêtes HTTP en JavaScript. Elle remplace XMLHttpRequest avec une syntaxe plus simple basée sur les Promises.
🌐 Méthodes HTTP
GET Récupérer
// GET : Récupérer des données
const res = await fetch('/api/users');
const data = await res.json();
// Avec query params
const url = '/api/users?page=1&limit=10';
const res = await fetch(url);
POST Créer
// POST : Créer une ressource
const res = await fetch('/api/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ name: 'Alice' })
});
PUT Modifier
// PUT : Mettre à jour (complet)
const res = await fetch('/api/users/1', {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ name: 'Bob' })
});
DELETE Supprimer
// DELETE : Supprimer une ressource
const res = await fetch('/api/users/1', {
method: 'DELETE'
});
if (res.ok) {
console.log('Supprimé !');
}
📝 Exemple Complet avec Gestion d'Erreurs
async function fetchUser(id) {
try {
const res = await fetch(`/api/users/${id}`);
// Vérifier le statut HTTP
if (!res.ok) {
throw new Error(`HTTP ${res.status}: ${res.statusText}`);
}
const data = await res.json();
return data;
} catch (error) {
// Gérer les erreurs réseau ou parsing
console.error('Erreur:', error.message);
throw error;
}
}
// Headers personnalisés
const res = await fetch('/api/data', {
headers: {
'Authorization': 'Bearer TOKEN',
'Content-Type': 'application/json',
'Accept': 'application/json'
}
});
// Timeout (avec AbortController)
const controller = new AbortController();
setTimeout(() => controller.abort(), 5000); // 5s timeout
try {
const res = await fetch('/api/slow', {
signal: controller.signal
});
} catch (error) {
if (error.name === 'AbortError') {
console.log('Requête annulée (timeout)');
}
}
🎮 API Playground
Testez des requêtes sur des APIs publiques.
👥 Users
JSONPlaceholder
JSONPlaceholder
📝 Posts
JSONPlaceholder
JSONPlaceholder
✅ Todos
JSONPlaceholder
JSONPlaceholder
🎲 Random User
RandomUser API
RandomUser API
Sélectionnez un endpoint et cliquez sur Envoyer
📦 L'Objet Response
const res = await fetch('/api/data');
// Propriétés utiles
res.ok; // true si status 200-299
res.status; // 200, 404, 500...
res.statusText; // "OK", "Not Found"...
res.headers; // Headers object
res.url; // URL finale (après redirects)
// Méthodes de parsing
await res.json(); // Parse JSON
await res.text(); // Texte brut
await res.blob(); // Fichier binaire
await res.arrayBuffer(); // Buffer
await res.formData(); // FormData
// Clone (body ne peut être lu qu'une fois)
const clone = res.clone();
const data1 = await res.json();
const data2 = await clone.json(); // OK
Best Practice : Vérifiez toujours
res.ok avant de parser. Utilisez
AbortController pour les timeouts. Pour les requêtes POST/PUT, n'oubliez pas le header
Content-Type: application/json.