Get Started with Creating a RESTful API Endpoints in NodeJS and ExpressJS

By the end of this article you will be able to have a simple api endpoint developed in NodeJS and ExpressJS by building a simple app. The whole idea of RESTful API is to transfer data without minding about the backend languages.

This tutorial assumes an intermediate knowledge of javascript and experience working on the CLI. The source code for the final project can be found here

Create a project

Let's get started by creating app directory...

$ mkdir orders

$ cd orders

Initialize your app

Make sure you are in the root of you app folder

$ npm init

Press enter key for every questions that you are being asked in your CLI, this will create a package.json file

Note: Don't be scared if you dont use npm, remember, it is the package manager if you use yarm, it's okey, there are the same.

$ npm install express --save

Create server.js and app.js in our app root folder

This file help us to process http request and when running 'npm start' from cli, it calls server.js

server.js

// require http modules first

const http = require('http');

//import app.js file
const app = require('./app');

define port to be used
const port = process.env.PORT || 3100;
const server = http.createServer(app);

server.listen(port, () => {
    //    let's print a message when the server run successfully
    console.log("Server restarted successfully")
});

Define the file to call when running npm start

app.js

//import express
const express = require('express');

const app = express();

// Routes which should handle request

app.get("/orders", (req, res, next) => {
    res.json(["Orange","Apple","Watermellon"]);
});

//export app
module.exports = app;

Note: Open package.json and add this line

"scripts": {
    "start": "node server.js"
 },

Hello World

Now we can run our API in the browser by taking advantage of *npm start. *

Remember for now, every change we make, we have to restart the server again with the aid of npm start

$ npm start

JSON Array of data

GET /orders Fetch all orders

Install Dependecies

  • HTTP request logger middleware handling with mogan

$ npm i morgan

Expected result

app.js Update app.js file a little bit to add morgan

//import express
const express = require('express');
const app = express();

// import morgan package
const morgan = require('morgan');

//use it
app.use(morgan('dev'));
// Routes which should handle request

app.get("/orders", (req, res, next) => {
    res.json(["Orange","Apple","Watermellon"]);
});

//export app
module.exports = app;

This package helps to show the method in use, response-time and the status

  • We are going to parse incoming request bodies in a middleware before handlers

$ npm i body-parser

app.js

//import express
const express = require('express');
const app = express();

// import morgan package
const morgan = require('morgan');

//use it
app.use(morgan('dev'));
// Routes which should handle request

// import body-parser
const bodyParser = require('body-parser');
// let's use it
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());

app.get("/orders", (req, res, next) => {
    res.json(["Orange","Apple","Watermellon"]);
});

//export app
module.exports = app;
  • Because we don't want to run npm start every time we make change to our code, let's use *nodemon, *It detects every change we make and automatically restarting the node application

$ npm install --save-dev nodemon

Open package.json and update it

"scripts": {
    "start": "nodemon server.js"
 },

Postman

Postman allows you create collections of integration tests to ensure your API is working as expected. Tests are run in a specific order with each test being executed after the last is finished. Get the app here

Create data folder

This step is for creating dummy data

Create a folder in orders

$ mkdir data

Create a file with in data directory and call it orders.json

[
    {
        "id": 1,
        "title": "molestie tellus. Aenean egestas hendrerit neque. In ornare sagittis felis.",
        "description": "est, congue a, aliquet vel,"
    }
]

# Create routes folder

  • Create routes directory in the root of the node application

$ mkdir routes

  • Create orders.js file in routes

orders.js

const express = require('express');
const router = express.Router();

const orders = require('./../data/orders');

// handle incoming request to /users
router.get('/', (req, res, next) => {
    res.status(200).json({
       orders: orders
    });
});


module.exports = router;

.

  • app.js
const express = require('express');
const app = express();

// import morgan package
const morgan = require('morgan');
//use it
app.use(morgan('dev'));

// import body-parser
const bodyParser = require('body-parser');
// let's use it
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());

// defining routes
const ordersRoutes = require('./routes/orders')
app.use('/orders', ordersRoutes);


module.exports = app;

Cross-Origin Resource Sharing

CORS allows us to use web applications within browsers when domains aren't the same, We get away of restrict access policy from one domain to resources belonging to another domain. By building on top of the XMLHttpRequest object, CORS allows developers to work with the same idioms as same-domain requests.

How do we do this practice using ExpressJS?

Add these code snippets in app.js

app.use((req, res, next) => {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});

Handling Errors

What if an http request can't be found?

app.use((req, res, next) => {
    const error = new Error("Not found");
    error.status = 404;
    next(error);
});

app.use((error, req, res, next) => {
    res.status(error.status || 500 );
    res.json({
        error: {
            message: error.message
        }
    })
});

Thank you for going through the article, hope it is helpful.

Buy me a coffee