![]() |
Le API (Application Programming Interfaces) sono fondamentali nello sviluppo web moderno. Che tu stia costruendo un'app mobile, una SPA (single-page application) o collegando diversi sistemi, le API ti permettono di inviare e ricevere dati facilmente. In questa guida vedremo tutti i passaggi per creare una semplice API RESTful utilizzando JavaScript con Node.js ed Express.
Alla fine di questo articolo, sarai in grado di costruire un’API base che esegue operazioni CRUD (Create, Read, Update, Delete), senza dover cercare ulteriori informazioni altrove.
📦 Passaggio 1: Crea il tuo progetto
mkdir mia-api
cd mia-api
npm init -y
npm install express
Questo comando crea una nuova cartella, inizializza il progetto e installa Express — il framework web più popolare per Node.js.
🧱 Passaggio 2: Crea il server
// Importa Express
const express = require('express');
const app = express();
// Middleware per gestire i body JSON
app.use(express.json());
// Porta su cui gira il server
const PORT = 3000;
// Avvio del server
app.listen(PORT, () => {
console.log(`Server attivo su http://localhost:${PORT}`);
});
✅ Spiegazione: Questo codice imposta un server Express base e lo abilita a gestire dati in formato JSON.
🗃️ Passaggio 3: Dati di esempio
// Dati di esempio - una lista di libri
let books = [
{ id: 1, title: "L'Alchimista", author: "Paulo Coelho" },
{ id: 2, title: "1984", author: "George Orwell" },
];
🔍 Passaggio 4: Crea gli endpoint
🔹 GET - Leggere tutti i libri
app.get('/api/books', (req, res) => {
// Restituisce la lista completa dei libri
res.json(books);
});
🔹 GET - Leggere un libro specifico
app.get('/api/books/:id', (req, res) => {
const bookId = parseInt(req.params.id); // Converte l'ID in numero
const book = books.find(b => b.id === bookId);
if (!book) {
return res.status(404).json({ message: "Libro non trovato" });
}
res.json(book);
});
🔹 POST - Aggiungere un nuovo libro
app.post('/api/books', (req, res) => {
const { title, author } = req.body;
const newBook = {
id: books.length + 1,
title,
author
};
books.push(newBook);
res.status(201).json(newBook);
});
🔹 PUT - Aggiornare un libro esistente
app.put('/api/books/:id', (req, res) => {
const bookId = parseInt(req.params.id);
const { title, author } = req.body;
const book = books.find(b => b.id === bookId);
if (!book) {
return res.status(404).json({ message: "Libro non trovato" });
}
// Aggiorna le proprietà del libro
book.title = title || book.title;
book.author = author || book.author;
res.json(book);
});
🔹 DELETE - Eliminare un libro
app.delete('/api/books/:id', (req, res) => {
const bookId = parseInt(req.params.id);
books = books.filter(b => b.id !== bookId);
res.json({ message: "Libro eliminato con successo" });
});
✅ Passaggio 5: Testa la tua API
Puoi testare la tua API usando strumenti come:
- Postman (trovi una guida qui)
- curl
- Oppure semplicemente dal browser per le richieste GET (es:
http://localhost:3000/api/books)
🧪 Opzionale: Abilitare il supporto CORS
Se vuoi chiamare questa API da un frontend in esecuzione nel browser (come React o Vue), installa e abilita CORS (qui "Cos’è CORS e Come Gestirlo" trovi un approfondimento sul tema):
npm install cors
const cors = require('cors');
app.use(cors());
🎉 Conclusione
Ora hai costruito una API funzionante utilizzando JavaScript, Node.js ed Express! Puoi ampliarla collegandola a un vero database come MongoDB o PostgreSQL, aggiungendo autenticazione o distribuendola online.
Questa è la tua base — da qui, puoi costruire tutto ciò che vuoi 🚀
Follow me #techelopment
Official site: www.techelopment.it
facebook: Techelopment
instagram: @techelopment
X: techelopment
Bluesky: @techelopment
telegram: @techelopment_channel
whatsapp: Techelopment
youtube: @techelopment
