📡 Tutorial - API REST e Fetch

Impara a comunicare con le API REST

Cos'è un'API REST?

Un'API REST (Representational State Transfer) è un insieme di regole che permette a due applicazioni di comunicare. Attraverso una API REST puoi recuperare dati, crearli, modificarli e eliminarli da un server usando richieste HTTP.

Metodi HTTP Principali

GET - Recupera dati dal server
POST - Crea nuovi dati sul server
PUT - Aggiorna completamente un dato
PATCH - Aggiorna parzialmente un dato
DELETE - Elimina un dato dal server

L'API che Useremo

Utilizzeremo un server JSON locale accessibile a http://localhost:3000/api che contiene risorse diverse (utenti, todo, ecc.).

⚠️ Importante: Prima di iniziare gli esercizi, assicurati che il server sia avviato! Apri il terminale nella cartella server-api e digita: npm start

1. Fetch API - GET Request

La fetch API è il modo moderno per fare richieste HTTP in JavaScript.

Sintassi Base:

fetch('https://api.example.com/data') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Errore:', error));

Come Funziona:

  1. fetch(url) - Invia la richiesta al server
  2. .then(response => response.json()) - Converte la risposta in JSON
  3. .then(data => ...) - Ricevi e usa i dati
  4. .catch(error => ...) - Gestisci gli errori

Esempio Pratico:

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));

2. Fetch API - POST Request

Per inviare dati al server, usiamo il metodo POST.

Sintassi:

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));

3. Fetch API - DELETE Request

Per eliminare un dato dal server.

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));

4. Async/Await - Sintassi Moderna

Una sintassi più leggibile e facile da capire rispetto alle Promise.

Sintassi:

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();
✓ Vantaggi: Il codice è più leggibile e simile al codice sincrono tradizionale.

5. Gestione degli Errori

È importante gestire gli errori quando facciamo richieste HTTP.

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); });

6. Endpoint Disponibili sul Nostro Server

GET /api/users - Ottieni lista utenti
Esempio: http://localhost:3000/api/users
GET /api/users/:id - Ottieni un utente
Esempio: http://localhost:3000/api/users/1
POST /api/users - Crea nuovo utente
Body: { "name": "Mario", "email": "mario@example.com" }
PUT /api/users/:id - Aggiorna utente
Body: { "name": "Luigi", "email": "luigi@example.com" }
DELETE /api/users/:id - Elimina utente
Esempio: http://localhost:3000/api/users/1

Ora Sei Pronto!

Hai imparato i concetti fondamentali delle API REST e della Fetch API. Ora puoi procedere agli esercizi e metterli in pratica!

← Torna al Hub