1. Home
  2. Explore
  3. Computer Science
  4. Express.js REST API

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Express.js REST API

๐Ÿš€ Building a REST API with Express.js

This guide covers building a RESTful API using Express.js, a Node.js framework. It focuses on creating a To-Do application with various routes for managing tasks.

๐Ÿ› ๏ธ Project Setup

To begin developing an Express.js application, follow these initial setup steps:

๐Ÿ“‚ Project Directory Creation

First, create a dedicated directory for your application.

  • Open your terminal.

  • Navigate to your desired location (e.g., cd Desktop).

  • Create a new directory: mkdir todos-app.

  • Move into the new directory: cd todos-app.

  • Open the project in VS Code: code . (ensure code command is set up, otherwise open VS Code manually).

๐Ÿ“ฆ Node.js Application Initialization

Express.js runs on Node.js, so you need to initialize a Node.js project.

  • Open the integrated terminal in VS Code.

  • Initialize the project: npm init -y.

  • This command creates a package.json file, which manages project metadata and dependencies.

๐ŸŒ Installing Express.js

Express is the only core dependency needed for this REST API.

  • Install Express: npm install express.

  • This adds Express to your package.json and creates a node_modules directory.

๐Ÿ’ก Creating the Express Server

The server logic will reside in index.js (or main.js).

  1. Import Express:

      const express = require('express');
  2. Create Express App:

      const app = express();
    • app is your Express application instance.

  3. Listen on a Port:

      const PORT = 3000;
      app.listen(PORT, () => {
          console.log(`Server listening on port ${PORT}`);
      });
    • The app.listen() method starts the server, making it listen for incoming requests on the specified port (e.g., 3000).

    • The callback function executes once the server successfully starts.

๐Ÿƒ Running the Application

To run your Express application:

  • In the terminal, execute: node index.js.

  • You should see the message: Server listening on port 3000.

๐Ÿ”„ Hot Reloading with Nodemon

For development, Nodemon automatically restarts the server when file changes are detected.

  • Install Nodemon globally: npm install -g nodemon.

    • Mac/Linux users might need sudo npm install -g nodemon.

  • Configure package.json: Add a dev script.

  • Run with Nodemon: npm run dev.

    • Now, changes to your index.js file will automatically restart the server.

๐Ÿ›ฃ๏ธ Defining API Routes

RESTful APIs expose routes (endpoints) to perform operations. Express uses app.VERB(path, callback) to define these.

๐Ÿ“ Global To-Do Data Store

For simplicity, a global array todos will store our to-do items in memory.

let todos = []; // This will reset on server restart

โ†”๏ธ Request and Response Objects

Every route handler receives two primary objects:

  • req (Request): Contains information about the incoming HTTP request, such as parameters, body, headers, and query strings.

  • res (Response): Used to send back the HTTP response to the client, including data, status codes, and headers.

๐Ÿงน Middleware: express.json()

Before handling routes that receive JSON data in the request body (like POST or PUT), you need to tell Express to parse incoming JSON.

  • Add this middleware early in your index.js file:

    app.use(express.json());
  • Middleware functions have access to the request and response objects and the next middleware function. They can modify these objects, end the request-response cycle, or pass control to the next middleware. express.json() parses the JSON body and makes it available on req.body.

๐Ÿ“ฆ UUID for Unique IDs

To generate unique identifiers for to-do items:

  • Install uuid: npm install uuid.

  • Import v4:

    const { v4: uuidv4 } = require('uuid'); // Renamed for clarity
  • Use uuidv4() to generate a new ID: id: uuidv4().


๐ŸŽฏ To-Do Application Routes

Let's implement the core CRUD (Create, Read, Update, Delete) operations for our To-Do application.

โžก๏ธ GET All To-Do's (/todos)

This route fetches all existing to-do items.

  • Verb: GET

  • Path: /todos

  • Handler:

    app.get('/todos', (req, res) => {
        // In a real app, this would fetch from a database
        return res.json(todos);
    });
  • Testing:

    • Browser: localhost:3000/todos

    • Postman/Insomnia: Send a GET request to http://localhost:3000/todos.

โž• Add a To-Do (/todos)

This route adds a new to-do item to the list.

  • Verb: POST

  • Path: /todos

  • Request Body: Expects a JSON object with a title property (e.g., { "title": "Pet the cat" }).

  • Handler:

    app.post('/todos', (req, res) => {
        const { title } = req.body; // Destructure title from request body
        if (!title) {
            return res.status(400).json({ message: 'Title is required' });
        }
        const newTodo = {
            id: uuidv4(), // Generate unique ID
            title,
            completed: false,
        };
        todos.push(newTodo);
        return res.status(201).json(newTodo); // Respond with the newly created to-do
    });
  • Testing in Postman:

    • Set method to POST.

    • URL: http://localhost:3000/todos.

    • Go to Body tab, select raw and JSON.

    • Enter JSON: {"title": "Clean the house"}.

    • Send the request. The response should be the added to-do item.

๐Ÿ”Ž GET One To-Do (/todos/:id)

This route retrieves a single to-do item by its unique ID.

  • Verb: GET

  • Path: /todos/:id

    • :id is a route parameter, indicating a dynamic part of the URL.

  • Handler:

    app.get('/todos/:id', (req, res) => {
        const { id } = req.params; // Get ID from route parameters
        const todo = todos.find(t => t.id === id);
    
        if (!todo) {
            return res.status(404).json({ message: 'To-do not found' });
        }
        return res.json(todo);
    });
  • Testing in Postman:

    • First, add a to-do using the POST route and copy its id.

    • Set method to GET.

    • URL: http://localhost:3000/todos/<copied_id>.

    • Send the request. The response should be the specific to-do item.

๐Ÿ”„ Update a To-Do (/todos/:id)

This route toggles the completed status of a to-do item.

  • Verb: PUT

  • Path: /todos/:id

  • Handler:

    app.put('/todos/:id', (req, res) => {
        const { id } = req.params;
        const todoIndex = todos.findIndex(t => t.id === id);
    
        if (todoIndex === -1) {
            return res.status(404).json({ message: 'To-do not found' });
        }
    
        todos[todoIndex].completed = !todos[todoIndex].completed; // Toggle completed status
        return res.json(todos[todoIndex]); // Respond with the updated to-do
    });
  • Testing in Postman:

    • First, add a to-do and copy its id.

    • Set method to PUT.

    • URL: http://localhost:3000/todos/<copied_id>.

    • Send the request. The completed status in the response should toggle.

๐Ÿ—‘๏ธ Delete a To-Do (/todos/:id)

This route removes a to-do item from the list.

  • Verb: DELETE

  • Path: /todos/:id

  • Handler:

    app.delete('/todos/:id', (req, res) => {
        const { id } = req.params;
        const initialLength = todos.length;
        todos = todos.filter(t => t.id !== id); // Filter out the deleted to-do
    
        if (todos.length === initialLength) {
            return res.status(404).json({ message: 'To-do not found' });
        }
        return res.status(200).json({ message: 'To-do deleted successfully', remainingTodos: todos }); // Respond with remaining todos
    });
  • Testing in Postman:

    • First, add a to-do and copy its id.

    • Set method to DELETE.

    • URL: http://localhost:3000/todos/<copied_id>.

    • Send the request. Then, use the GET /todos route to confirm deletion.


๐Ÿ—‚๏ธ Route Organization with Express Router

As an application grows, keeping all routes in one file (index.js) becomes unmanageable. Express Router helps organize routes into separate modules.

๐Ÿ“‚ Creating a Routes Directory

  • Create a routes directory: mkdir routes.

  • Inside, create todos.js for to-do related routes.

๐Ÿ“ todos.js Content

  1. Import Express Router:

      const express = require('express');
      const router = express.Router(); // Create a new router instance
      const { v4: uuidv4 } = require('uuid'); // Also need uuid here
    
      // Global todos array (for this example, still in memory)
      let todos = [];
  2. Replace app with router: Change all app.get, app.post, etc., to router.get, router.post.

  3. Export the Router:

      module.exports = router;
  4. Remove duplicate path segments: If all routes in todos.js start with /todos, you can remove /todos from each route definition within todos.js and specify it once when using the router.

    • Example: router.get('/', ...) instead of router.get('/todos', ...).

    • Example: router.get('/:id', ...) instead of router.get('/todos/:id', ...).

๐Ÿ”— Integrating Router in index.js

  1. Import the To-Do Router:

      const todosRouter = require('./routes/todos');
  2. Use the Router with a Base Path:

      app.use('/todos', todosRouter);
    • app.use('/todos', todosRouter) means all routes defined in todosRouter will be prefixed with /todos. So, router.get('/') in todos.js becomes GET /todos in the main app, and router.get('/:id') becomes GET /todos/:id.


๐Ÿ›ก๏ธ Middleware Deep Dive

Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application's request-response cycle.

โš™๏ธ How Middleware Works

  • A client makes a request.

  • The request passes through a chain of middleware functions.

  • Each middleware can:

    • Execute any code.

    • Make changes to the request and the response objects.

    • End the request-response cycle (e.g., by sending a response).

    • Call the next middleware in the stack (next()).

  • If next() is not called, the request will be left hanging unless the middleware itself sends a response.

๐Ÿ”‘ Authentication Middleware Example

Let's create a simple authentication middleware to check for an authenticated header.

  1. Create middleware/check-auth.js:

      const checkAuth = (req, res, next) => {
          const authenticated = req.header('authenticated'); // Get header value
    
          if (authenticated === 'yes') {
              next(); // User is authenticated, proceed to next middleware or route handler
          } else {
              return res.status(403).json({ message: 'Not authenticated' }); // Forbidden error
          }
      };
    
      module.exports = checkAuth;
  2. Integrate Middleware into Routes:

    • In routes/todos.js, import the middleware:

    • Add checkAuth as a second argument to any route that requires authentication:

      router.get('/', checkAuth, (req, res) => {
          return res.json(todos);
      });
      
      router.post('/', checkAuth, (req, res) => {
          // ... (rest of the post logic)
      });
      // Apply to all other routes as needed
    • Middleware Order: Middleware functions are executed in the order they are defined. If checkAuth is placed before the route handler, it runs first.

๐Ÿงช Testing Authentication

  • In Postman:

    • Go to the Headers tab for your request.

    • Add a key-value pair: authenticated: yes. The request should succeed.

    • Change to authenticated: no. The request should fail with a 403 Forbidden status and a Not authenticated message.


This structured approach demonstrates the core principles of building RESTful APIs with Express.js, covering setup, routing, and middleware for a robust and organized application.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent