Creating a RESTfull API with Node.js

Through this post I am going to implement a simple REST API with Node.js.

So, at the very first begining, we’ll see what is meant by REST API.

A REST API (also known as RESTful API) is an application programming interface that conforms to the constraints of REST architecture. REST is an acronym for Representational State Transfer. A REST API is a way for two computer systems to communicate over HTTP in a similar way to web browsers and servers.

When a request is made via a RESTful API, it transfers a representation of the state of the resource to the requester. This information, or representation, is delivered in one of several formats via HTTP: JSON, HTML, XLT, or plain text. JSON is the most generally popular because, despite its name, it’s language agnostic, as well as readable by both humans and machines.

In order for an API to be considered RESTful, it has to conform to these criteria:

  1. Client-Server: made up of clients, servers, and resources, with requests managed through HTTP.
  2. Stateless: no client information is stored between requests and each request is separate and unconnected.
  3. Cacheable: streamlines client-server interactions.
  4. Layered system: client need not know whether it’s communicating with the actual server, a proxy, or any other intermediary.
  5. Uniform interface: information is transferred in a standard form.
  6. Code on demand (optional constraint): permits a clients code or applets to be downloaded and to be used within the application.

In REST API there are 4 main methods (CRUD operations). They are:

  1. POST (Create) - creates a new record
  2. GET (Read) - returns requested data
  3. PUT/PATCH (Update) - updates an existing record
  4. DELETE (Delete) - deletes an existing record

With having an idea of REST API, we’ll move to implement a simple CRUD REST application.

First we’ll look at how our API look likes:

So, in our API there going to be two resources: products and orders. Through our API, we can,

  1. create product or order. (POST)
  2. read details of products or orders. (GET)
  3. read an individual product or order details using order id or product id. (GET)
  4. update product detalis. (PATCH)
  5. delete a product or order. (DELETE)

Pre-requisities

Node.js: To install Node.js, you can use here.

Postman: Install Postman as a Chrome extension. To install Postman you can visit here and click on ‘Add to Chrome’.

Here, I am using Visual Studio Code to write and execute codes. You can use any IDE or code editor according to your choice.

So, let’s get started.

Step 01

Create a directory and navigate to that director using following commands in command prompt.

mkdir Node-Rest-Shop
cd Node-Rest-Shop

To initialize the project use npm init command as follows:

Once you run through the npm init steps above, a package.json file will be generated and placed in the current directory. Open your project folder through IDE. Then you can see the generatedpackage.json file.

Step 02

Then we are going to install certain dependancies needed for the implementation.

Express is a web framework which can be used along with Node.js. This web framework will allow you to create Restful APIs, with the help of helper methods, middle layers to configure your application.

npm install --save express

Step 03

Create below JavaScript files calling server.js, app.js, order.js and products.js.

My folder structure is as follows:

sever.js

const http = require('http');
const app = require('./app');
const port = process.env.port || 3000;
const server = http.createServer(app);
server.listen(port);

app.js

const express = require('express');
const app = express();
const productRoutes = require('path to products folder'); // in my ./api/routes/productsconst orderRoutes = require('path to products folder'); //in my ./api/routes/orderapp.use('/products', productRoutes);
app.use('/order', orderRoutes);
module.exports = app;

order.js

// To setup order related routes.const express = require('express');
const router = express.Router();
router.get('/', (req, res, next) => {
res.status(200).json({
message: 'Orders were fetched'
});
});
router.post('/', (req, res, next) => {
res.status(201).json({
message: 'Order was created'
});
});
router.get('/:orderId', (req, res, next) => {
res.status(200).json({
message: 'Order details',
id: req.params.orderId
});
});
router.delete('/:orderId', (req, res, next) => {
res.status(200).json({
message: 'Order deleted',
id: req.params.orderId
});
});
module.exports = router;

products.js

// To setup product related routes.const express = require('express');
const router = express.Router();
router.get('/', (req, res, next) => {
res.status(200).json({
message: 'Handling GET requests to /products'
});
});
router.post('/', (req, res, next) => {
res.status(201).json({
message: 'Handling POST requests to /products'
});
});
//Get details of a single product using product idrouter.get('/:productId', (req, res, next) => {
const id = req.params.productId;
if(id === 'special'){
res.status(200).json({
message: 'You discovered the special ID',
id: id
});
} else {
res.status(200).json({
message: 'You passed an ID'
});
}
});
router.patch('/:productId', (req, res, next) => {
res.status(200).json({
message: 'Updated produt!!'
});
});
router.delete('/:productId', (req, res, next) => {
res.status(200).json({
message: 'Deleted produt!!'
});
});

Step 06

After adding code, now you should run the server by typing the command,

node server.js

This will start the server and keep running. Since we are running on our local machine, this will run on port 3000.

Now, the next step is to check whether the handlers are working properly or not.

For that, we will use the Postman. You can test whether the CRUD operations are working properly by using localhost:3000/products

POST & GET requests of products

For an individual detail pass the url as localhost:3000/products/{id}

GET, PATCH & DELETE requests for an individual product

The requests for orders can also see as above.

With this, we come to an end of this article on “Creating a RESTfull API with Node.js”.

Thank You…..

Undergraduate at University of Moratuwa

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store