Creating a Basic REST API with NodeJS and ExpressJS: Creating the Controllers

Capítulo 70

Estimated reading time: 4 minutes

+ Exercise
Audio Icon

Listen in audio

0:00 / 0:00

One of the most important elements in creating a basic REST API with NodeJS and ExpressJS is creating the controllers. Controllers are responsible for managing server requests and responses, facilitating communication between the client and the server.

1. Starting the project

To get started, you need to install NodeJS and ExpressJS on your system. You can do this using the npm package manager. In the terminal, type the following commands:

npm init -y
npm install express --save

This will initialize a new NodeJS project and install ExpressJS.

2. Creating the server

With ExpressJS installed, you can create a basic server. Create a new file called 'server.js' and add the following code:

const express = require('express');
const app = express();
const port = 3000;

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});

This code creates a new ExpressJS server that listens on port 3000.

Continue in our app.
  • Listen to the audio with the screen off.
  • Earn a certificate upon completion.
  • Over 5000 courses for you to explore!
Or continue reading below...
Download App

Download the app

3. Creating the controllers

Now, let's create the controllers. In a REST API, controllers are functions that handle HTTP requests and send a response. Let's create a controller for each CRUD operation (Create, Read, Update, Delete).

Create a new directory called 'controllers' and inside it create a file called 'userController.js'. In this file, add the following code:

exports.getAllUsers = (req, res) => {
  res.status(200).json({
    status: 'success',
    date: {
      users: []
    }
  });
};

exports.createUser = (req, res) => {
  res.status(201).json({
    status: 'success',
    date: {
      user: {}
    }
  });
};

exports.getUser = (req, res) => {
  res.status(200).json({
    status: 'success',
    date: {
      user: {}
    }
  });
};

exports.updateUser = (req, res) => {
  res.status(200).json({
    status: 'success',
    date: {
      user: {}
    }
  });
};

exports.deleteUser = (req, res) => {
  res.status(204).json({
    status: 'success',
    date: null
  });
};

These are the basic controllers for CRUD operations. They aren't doing much right now, but you can expand them to interact with a database or other data source.

4. Configuring the routes

With the controllers created, you need to configure the routes. Routes are the URLs that clients use to access controller functions.

Create a new directory called 'routes' and inside it create a file called 'userRoutes.js'. In this file, add the following code:

const express = require('express');
const userController = require('../controllers/userController');
const router = express.Router();

router.route('/')
  .get(userController.getAllUsers)
  .post(userController.createUser);

router.route('/:id')
  .get(userController.getUser)
  .patch(userController.updateUser)
  .delete(userController.deleteUser);

module.exports = router;

This code creates the routes to the controller functions. Now, if you start the server and go to 'http://localhost:3000/', you can use CRUD operations in the API.

In summary, building a basic REST API with NodeJS and ExpressJS involves creating a server, defining controllers to handle requests and responses, and setting up routes so clients can access controller functions . With these building blocks, you can create a powerful and flexible REST API.

Now answer the exercise about the content:

What is the role of controllers in a basic REST API built with NodeJS and ExpressJS?

You are right! Congratulations, now go to the next page

You missed! Try again.

Controllers in a basic REST API built with NodeJS and ExpressJS are responsible for managing server requests and responses. They facilitate communication between the client and the server by handling the logic that determines how to read, modify, create, and delete resources.

Next chapter

Creating a Basic REST API with NodeJS and ExpressJS: Implementing the HTTP Methods

Arrow Right Icon
Free Ebook cover How to create APIs in NodeJS from basic to advanced
47%

How to create APIs in NodeJS from basic to advanced

5

(1)

149 pages

Download the app to earn free Certification and listen to the courses in the background, even with the screen off.