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.