Files
esercizi-web/JS_Esercizi 11 - API/tutorial/index.html
2026-02-05 11:57:28 +01:00

188 lines
6.7 KiB
HTML

<!DOCTYPE html>
<html lang="it">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tutorial - API REST e Fetch</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container">
<h1>📡 Tutorial - API REST e Fetch</h1>
<p class="subtitle">Impara a comunicare con le API REST</p>
<h2>Cos'è un'API REST?</h2>
<p>
Un'API REST (Representational State Transfer) è un insieme di regole che permette a due applicazioni di comunicare.
Attraverso una API REST puoi <strong>recuperare dati</strong>, <strong>crearli</strong>, <strong>modificarli</strong> e <strong>eliminarli</strong>
da un server usando richieste HTTP.
</p>
<h2>Metodi HTTP Principali</h2>
<div class="endpoint-list">
<div class="endpoint-item">
<strong>GET</strong> - Recupera dati dal server
</div>
<div class="endpoint-item">
<strong>POST</strong> - Crea nuovi dati sul server
</div>
<div class="endpoint-item">
<strong>PUT</strong> - Aggiorna completamente un dato
</div>
<div class="endpoint-item">
<strong>PATCH</strong> - Aggiorna parzialmente un dato
</div>
<div class="endpoint-item">
<strong>DELETE</strong> - Elimina un dato dal server
</div>
</div>
<h2>L'API che Useremo</h2>
<p>
Utilizzeremo un server JSON locale accessibile a <code>http://localhost:3000/api</code>
che contiene risorse diverse (utenti, todo, ecc.).
</p>
<div class="note">
<strong>⚠️ Importante:</strong> Prima di iniziare gli esercizi, assicurati che il server sia avviato!
Apri il terminale nella cartella <code>server-api</code> e digita: <code>npm start</code>
</div>
<h2>1. Fetch API - GET Request</h2>
<p>La fetch API è il modo moderno per fare richieste HTTP in JavaScript.</p>
<h3>Sintassi Base:</h3>
<div class="code-block">
<code>fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Errore:', error));</code>
</div>
<h3>Come Funziona:</h3>
<ol>
<li><strong>fetch(url)</strong> - Invia la richiesta al server</li>
<li><strong>.then(response => response.json())</strong> - Converte la risposta in JSON</li>
<li><strong>.then(data => ...)</strong> - Ricevi e usa i dati</li>
<li><strong>.catch(error => ...)</strong> - Gestisci gli errori</li>
</ol>
<h3>Esempio Pratico:</h3>
<div class="code-block">
<code>fetch('http://localhost:3000/api/users')
.then(response => response.json())
.then(users => {
console.log('Utenti ricevuti:', users);
users.forEach(user => {
console.log(`${user.name} - ${user.email}`);
});
})
.catch(error => console.error('Errore:', error));</code>
</div>
<h2>2. Fetch API - POST Request</h2>
<p>Per inviare dati al server, usiamo il metodo POST.</p>
<h3>Sintassi:</h3>
<div class="code-block">
<code>fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'Mario',
email: 'mario@example.com'
})
})
.then(response => response.json())
.then(data => console.log('Creato:', data))
.catch(error => console.error('Errore:', error));</code>
</div>
<h2>3. Fetch API - DELETE Request</h2>
<p>Per eliminare un dato dal server.</p>
<div class="code-block">
<code>fetch('https://api.example.com/users/1', {
method: 'DELETE'
})
.then(response => response.json())
.then(data => console.log('Eliminato:', data))
.catch(error => console.error('Errore:', error));</code>
</div>
<h2>4. Async/Await - Sintassi Moderna</h2>
<p>Una sintassi più leggibile e facile da capire rispetto alle Promise.</p>
<h3>Sintassi:</h3>
<div class="code-block">
<code>async function fetchUsers() {
try {
const response = await fetch('http://localhost:3000/api/users');
const users = await response.json();
console.log('Utenti:', users);
} catch (error) {
console.error('Errore:', error);
}
}
fetchUsers();</code>
</div>
<div class="success">
<strong>✓ Vantaggi:</strong> Il codice è più leggibile e simile al codice sincrono tradizionale.
</div>
<h2>5. Gestione degli Errori</h2>
<p>È importante gestire gli errori quando facciamo richieste HTTP.</p>
<div class="code-block">
<code>fetch('http://localhost:3000/api/users')
.then(response => {
if (!response.ok) {
throw new Error(`Errore HTTP: ${response.status}`);
}
return response.json();
})
.then(data => console.log(data))
.catch(error => {
console.error('Errore nella richiesta:', error.message);
});</code>
</div>
<h2>6. Endpoint Disponibili sul Nostro Server</h2>
<div class="endpoint-list">
<div class="endpoint-item">
<strong>GET /api/users</strong> - Ottieni lista utenti<br>
<small>Esempio: http://localhost:3000/api/users</small>
</div>
<div class="endpoint-item">
<strong>GET /api/users/:id</strong> - Ottieni un utente<br>
<small>Esempio: http://localhost:3000/api/users/1</small>
</div>
<div class="endpoint-item">
<strong>POST /api/users</strong> - Crea nuovo utente<br>
<small>Body: { "name": "Mario", "email": "mario@example.com" }</small>
</div>
<div class="endpoint-item">
<strong>PUT /api/users/:id</strong> - Aggiorna utente<br>
<small>Body: { "name": "Luigi", "email": "luigi@example.com" }</small>
</div>
<div class="endpoint-item">
<strong>DELETE /api/users/:id</strong> - Elimina utente<br>
<small>Esempio: http://localhost:3000/api/users/1</small>
</div>
</div>
<h2>Ora Sei Pronto!</h2>
<p>
Hai imparato i concetti fondamentali delle API REST e della Fetch API.
Ora puoi procedere agli esercizi e metterli in pratica!
</p>
<a href="../index.html" class="back-button">← Torna al Hub</a>
</div>
</body>
</html>