🟢 Node.js Q34 / 118

How do you create a REST API in Node.js?

AI-Powered Answer ✓ Answered

Creating a REST API in Node.js typically involves using a web framework like Express.js, which simplifies handling HTTP requests, routing, and middleware. This guide will walk you through the fundamental steps to build a basic REST API.

Prerequisites

  • Node.js installed on your system (includes npm, the Node.js package manager).
  • Basic understanding of JavaScript and command-line interface.

Step 1: Initialize Your Project

Open your terminal, navigate to your desired project directory, and initialize a new Node.js project. This will create a package.json file.

bash
mkdir my-rest-api
cd my-rest-api
npm init -y

Step 2: Install Express.js

Install the Express.js framework, which will handle the server-side logic and routing.

bash
npm install express

Step 3: Create Your Server File (e.g., `app.js` or `index.js`)

Create a new file (e.g., app.js) in your project's root directory. This file will contain your Express application setup.

javascript
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;

// Middleware to parse JSON bodies
app.use(express.json());

// Basic route
app.get('/', (req, res) => {
  res.send('Welcome to the Node.js REST API!');
});

// Start the server
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

Step 4: Define API Routes and Endpoints

REST APIs typically interact with resources. Let's create some dummy data and define routes for a 'products' resource using common HTTP methods (GET, POST, PUT, DELETE).

javascript
let products = [
  { id: 1, name: 'Laptop', price: 1200 },
  { id: 2, name: 'Mouse', price: 25 },
  { id: 3, name: 'Keyboard', price: 75 }
];

// GET all products
app.get('/api/products', (req, res) => {
  res.json(products);
});

// GET a single product by ID
app.get('/api/products/:id', (req, res) => {
  const id = parseInt(req.params.id);
  const product = products.find(p => p.id === id);
  if (!product) return res.status(404).send('Product not found.');
  res.json(product);
});

// POST a new product
app.post('/api/products', (req, res) => {
  const newProduct = {
    id: products.length > 0 ? Math.max(...products.map(p => p.id)) + 1 : 1,
    name: req.body.name,
    price: req.body.price
  };
  if (!newProduct.name || !newProduct.price) {
    return res.status(400).send('Name and price are required.');
  }
  products.push(newProduct);
  res.status(201).json(newProduct);
});

// PUT (update) an existing product
app.put('/api/products/:id', (req, res) => {
  const id = parseInt(req.params.id);
  let product = products.find(p => p.id === id);
  if (!product) return res.status(404).send('Product not found.');

  product.name = req.body.name || product.name;
  product.price = req.body.price || product.price;
  res.json(product);
});

// DELETE a product
app.delete('/api/products/:id', (req, res) => {
  const id = parseInt(req.params.id);
  const initialLength = products.length;
  products = products.filter(p => p.id !== id);

  if (products.length === initialLength) {
    return res.status(404).send('Product not found.');
  }
  res.status(204).send(); // No content to send back
});

Step 5: Run Your API

Save your app.js file and run it from your terminal:

bash
node app.js

You should see the message "Server running on port 3000" (or your chosen port). You can now test your API using tools like Postman, Insomnia, or curl.

Example API Interactions

  • GET all products: GET http://localhost:3000/api/products
  • GET product by ID: GET http://localhost:3000/api/products/1
  • POST new product: POST http://localhost:3000/api/products with Content-Type: application/json and body: {"name": "Monitor", "price": 300}
  • PUT update product: PUT http://localhost:3000/api/products/1 with Content-Type: application/json and body: {"price": 1250}
  • DELETE product: DELETE http://localhost:3000/api/products/2

Next Steps & Best Practices

  • Database Integration: Replace in-memory data with a persistent database like MongoDB (using Mongoose), PostgreSQL (using Sequelize/TypeORM), or MySQL.
  • Error Handling: Implement robust error handling middleware.
  • Authentication & Authorization: Secure your API with strategies like JWT (JSON Web Tokens) or OAuth.
  • Validation: Use libraries like Joi or Express-validator to validate incoming request data.
  • Modularity: Organize your routes, controllers, and models into separate files and folders for better maintainability (e.g., using express.Router()).
  • Environment Variables: Use dotenv to manage sensitive information and configuration.
  • Testing: Write unit and integration tests for your API endpoints.
  • Logging: Implement a logging solution (e.g., Winston, Morgan) to track requests and errors.