How do I create REST APIs with JavaScript

Creating REST APIs with JavaScript can be accomplished using various frameworks and libraries. Below is a basic example of how to create a simple REST API using Node.js with the Express framework:

const express = require('express'); const app = express(); const port = 3000; app.use(express.json()); // Sample data let users = [ { id: 1, name: 'John Doe' }, { id: 2, name: 'Jane Doe' } ]; // GET all users app.get('/users', (req, res) => { res.json(users); }); // GET a single user by ID app.get('/users/:id', (req, res) => { const user = users.find(u => u.id === parseInt(req.params.id)); if (!user) return res.status(404).send('User not found.'); res.json(user); }); // POST a new user app.post('/users', (req, res) => { const newUser = { id: users.length + 1, name: req.body.name }; users.push(newUser); res.status(201).json(newUser); }); // Start the server app.listen(port, () => { console.log(`Server running at http://localhost:${port}`); });

REST API JavaScript Node.js Express web development