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

Página 70

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.

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.

Next page of the Free Ebook:

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

Earn your Certificate for this Course for Free! by downloading the Cursa app and reading the ebook there. Available on Google Play or App Store!

Get it on Google Play Get it on App Store

+ 6.5 million
students

Free and Valid
Certificate with QR Code

48 thousand free
exercises

4.8/5 rating in
app stores

Free courses in
video, audio and text