Impara a comunicare con le 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.
Utilizzeremo un server JSON locale accessibile a http://localhost:3000/api
che contiene risorse diverse (utenti, todo, ecc.).
server-api e digita: npm start
La fetch API è il modo moderno per fare richieste HTTP in JavaScript.
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Errore:', error));
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));
Per inviare dati al server, usiamo il metodo POST.
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));
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));
Una sintassi più leggibile e facile da capire rispetto alle Promise.
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();
È 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);
});
Hai imparato i concetti fondamentali delle API REST e della Fetch API. Ora puoi procedere agli esercizi e metterli in pratica!
← Torna al Hub