10.3. Building a Basic REST API with NodeJS and ExpressJS: Initial Project Setup
To start creating a basic REST API with NodeJS and ExpressJS, you must first understand what a REST API is. REST (Representational State Transfer) API is a style of software architecture that defines the implementation of a web service. They allow interaction between independent applications through HTTP requests, returning data that can be manipulated and used to develop and operate different types of applications.
NodeJS is a platform built on Google Chrome's JavaScript engine to easily build fast and scalable web applications. ExpressJS, on the other hand, is a web application framework expressed by NodeJS that provides a robust set of features for web and mobile applications.
Initial project setup
To begin with, you need to install NodeJS and NPM (Node Package Manager) on your machine. After installation, you can check the version of NodeJS and NPM using the commands: node -v and npm -v respectively in the terminal.
After installing NodeJS and NPM, create a new folder for your project and navigate to it using the terminal. Inside the project folder, run the npm init command to create a new package.json file. This file will contain information about your project and the dependencies that will be installed later.
Next, you need to install ExpressJS. For this, use the command: npm install express --save. The --save parameter will add ExpressJS as a dependency in your package.json file.
After installing ExpressJS, create a new file called server.js. This will be the entry point for your application. Inside server.js, you need to import express and configure the server to listen on a specific port.
const express = require('express');
const app = express();
const port = 3000;
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
Now, if you run the node server.js command, you will see the message "Server is running on port 3000" in the console. This means your server is configured and listening on port 3000.
Creating routes
The next step is to create some routes for your application. Routes are defined using methods of the express object, where each method corresponds to an HTTP method (get, post, put, delete, etc.).
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.post('/', (req, res) => {
res.send('Got a POST request');
});
app.put('/', (req, res) => {
res.send('Got a PUT request');
});
app.delete('/', (req, res) => {
res.send('Got a DELETE request');
});
The above routes will respond to GET, POST, PUT, and DELETE requests at the root of your site.
With that, you already have a basic REST API set up with NodeJS and ExpressJS. In the next chapter, we'll explore how to connect your API to a database and how to handle data received from client requests.