If you're a JavaScript developer looking to build scalable backend services, Express.js is a great starting point. In this guide, you’ll learn how to build a basic RESTful API using Node.js and Express.js.
๐ง Prerequisites
- Basic knowledge of JavaScript
 - Node.js and npm installed
 - Code editor (like VS Code)
 - Postman or curl for testing
 
๐ Step 1: Initialize a Node.js Project
mkdir express-api cd express-api npm init -y
๐ฆ Step 2: Install Express.js
npm install express
๐ Step 3: Create the Main Server File
Create a file named server.js and add the following code:
const express = require('express');
const app = express();
const PORT = 3000;
app.use(express.json());
app.get('/', (req, res) => {
  res.send('Welcome to the Express.js API!');
});
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});
  
  ๐ Step 4: Define Routes for the API
Let’s create a simple CRUD API for managing a list of books:
let books = [
  { id: 1, title: '1984', author: 'George Orwell' },
  { id: 2, title: 'The Alchemist', author: 'Paulo Coelho' }
];
// Get all books
app.get('/api/books', (req, res) => {
  res.json(books);
});
// Get book by ID
app.get('/api/books/:id', (req, res) => {
  const book = books.find(b => b.id === parseInt(req.params.id));
  if (!book) return res.status(404).send('Book not found');
  res.json(book);
});
// Add new book
app.post('/api/books', (req, res) => {
  const newBook = {
    id: books.length + 1,
    title: req.body.title,
    author: req.body.author
  };
  books.push(newBook);
  res.status(201).json(newBook);
});
// Update a book
app.put('/api/books/:id', (req, res) => {
  const book = books.find(b => b.id === parseInt(req.params.id));
  if (!book) return res.status(404).send('Book not found');
  book.title = req.body.title;
  book.author = req.body.author;
  res.json(book);
});
// Delete a book
app.delete('/api/books/:id', (req, res) => {
  books = books.filter(b => b.id !== parseInt(req.params.id));
  res.status(204).send();
});
  
  ๐ Step 5: Run and Test the API
Start the server:
node server.js
Use Postman or curl to test these endpoints:
GET /api/books– Get all booksGET /api/books/:id– Get a single bookPOST /api/books– Create a bookPUT /api/books/:id– Update a bookDELETE /api/books/:id– Delete a book
๐ Final Thoughts
This simple Express.js API is a solid foundation for more advanced backend services. From here, you can integrate a database like MongoDB or PostgreSQL, add validation with middleware, or implement authentication.
Thanks for reading! Feel free to leave a comment or reach out with questions.
Happy coding! ๐
Comments
Post a Comment