Day 2: Creating Routes and Controllers


In this tutorial, you’ll learn how to create and organize routes and controllers in an Express API. By the end of this lesson, you’ll have a well-structured API with multiple routes and controllers to handle different types of requests.


What You Will Learn Today:

  1. Organizing routes in Express
  2. Creating controllers to handle logic for each route
  3. Structuring your project for scalability
  4. Testing the new routes using Postman

Step 1: Organizing Routes in Express

As your API grows, it’s essential to keep your code organized. Instead of writing all your routes in index.js, you should separate them into different files for better maintainability. Today, we’ll move the user-related routes into a dedicated file.

Creating the Routes Directory

  1. Inside your project directory, create a new folder called routes. This will store all the route definitions for your API.
mkdir routes
  1. Inside the routes folder, create a new file called users.js. This file will handle all the routes related to users.
touch routes/users.js

Step 2: Defining User Routes

Next, we’ll move the user-related routes from index.js to the new users.js file.

Open routes/users.js and add the following code:

const express = require('express');
const router = express.Router();

// Get all users
router.get('/', (req, res) => {
  const users = [
    { id: 1, name: 'John Doe' },
    { id: 2, name: 'Jane Smith' },
    { id: 3, name: 'Alice Johnson' }
  ];
  res.json(users);
});

// Get a specific user by ID
router.get('/:id', (req, res) => {
  const userId = parseInt(req.params.id);
  const users = [
    { id: 1, name: 'John Doe' },
    { id: 2, name: 'Jane Smith' },
    { id: 3, name: 'Alice Johnson' }
  ];
  const user = users.find((u) => u.id === userId);

  if (user) {
    res.json(user);
  } else {
    res.status(404).json({ message: 'User not found' });
  }
});

module.exports = router;

Explanation:

  • router.get('/'): Defines a route that returns all users when the /api/users endpoint is accessed.
  • router.get('/:id'): Defines a route that returns a specific user based on their ID. The :id part in the URL is a route parameter, which allows us to pass dynamic values (in this case, the user ID).
  • res.status(404): If a user with the given ID is not found, the server responds with a 404 Not Found status code.
See also  Day 1: Setting Up Navigation with React Navigation

Step 3: Integrating the User Routes into the Main App

Now that we have defined the user routes, we need to integrate them into the main app. Open index.js and modify it as follows:

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

// Import the user routes
const userRoutes = require('./routes/users');

// Use the user routes under /api/users
app.use('/api/users', userRoutes);

// Basic route for the home page
app.get('/', (req, res) => {
  res.send('Welcome to my Express API!');
});

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

Explanation:

  • app.use('/api/users', userRoutes): This tells Express to use the user-related routes whenever the /api/users path is accessed. All the routes defined in users.js will be prefixed with /api/users.

Step 4: Creating Controllers

To further improve the structure of the code, let’s move the logic out of the route definitions and into separate controller functions. Controllers will handle the business logic of your API, keeping your routes clean and organized.

Creating the Controllers Directory

  1. Inside your project directory, create a folder called controllers. This will hold the logic for handling requests.
mkdir controllers
  1. Inside the controllers folder, create a new file called userController.js.
touch controllers/userController.js
  1. Open controllers/userController.js and define the following functions to handle requests related to users:
// Controller to get all users
exports.getAllUsers = (req, res) => {
  const users = [
    { id: 1, name: 'John Doe' },
    { id: 2, name: 'Jane Smith' },
    { id: 3, name: 'Alice Johnson' }
  ];
  res.json(users);
};

// Controller to get a user by ID
exports.getUserById = (req, res) => {
  const userId = parseInt(req.params.id);
  const users = [
    { id: 1, name: 'John Doe' },
    { id: 2, name: 'Jane Smith' },
    { id: 3, name: 'Alice Johnson' }
  ];
  const user = users.find((u) => u.id === userId);

  if (user) {
    res.json(user);
  } else {
    res.status(404).json({ message: 'User not found' });
  }
};

Explanation:

  • getAllUsers: This function handles the logic for returning all users.
  • getUserById: This function handles finding and returning a user by their ID.
See also  AI-powered Fake News Detection (Limited Scope with PHP)

Step 5: Using Controllers in Routes

Now that we have the logic in our controllers, we can update the routes to use these controller functions.

  1. Open routes/users.js and modify it as follows:
const express = require('express');
const router = express.Router();
const userController = require('../controllers/userController');

// Get all users
router.get('/', userController.getAllUsers);

// Get a user by ID
router.get('/:id', userController.getUserById);

module.exports = router;

Explanation:

  • userController.getAllUsers: We’re now using the getAllUsers function from the userController to handle the logic for this route.
  • userController.getUserById: Similarly, we use getUserById to handle the logic for fetching a specific user by ID.

Step 6: Testing the API in Postman

Let’s test the new routes to ensure everything is working correctly.

  1. Restart the server by running:
node index.js
  1. Open Postman and perform the following tests:
  • Get all users: Send a GET request to http://localhost:5000/api/users. You should receive a JSON response with the list of users.
  • Get a user by ID: Send a GET request to http://localhost:5000/api/users/1. You should receive the user with ID 1.

If everything is working correctly, you should see the data returned as expected. If the user is not found, you should see a 404 error with the message "User not found".


Step 7: Recap and Summary

In this tutorial, you learned how to create and organize routes and controllers in your Express API. Here’s a quick summary of what you’ve done:

  • Created a routes directory and moved the user-related routes into a separate file.
  • Defined route parameters to handle dynamic requests (e.g., fetching a user by ID).
  • Created a controllers directory and moved the business logic into controller functions.
  • Integrated the routes with the controller functions.
  • Tested the routes using Postman.
See also  Sending Emails with Gmail API in WordPress - A Comprehensive Guide

This structure is scalable and maintainable, allowing you to easily add more routes and controllers as your API grows.


Next Up: Day 3 – Connecting to a Database

In Day 3, we’ll connect the API to a database (using MongoDB or PostgreSQL) and start persisting real data. You’ll learn how to set up a database, create models, and interact with the database through your API.

Stay tuned for more advanced features tomorrow!


Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.