nodejs

How to Build REST API in 5 Different NodeJs Frameworks

By Rasyue | On May 26, 2020

Introduction

In this post, we are going to create an API endpoint using 5 different NodeJs frameworks. Let’s get started!

Now, before we start creating our API endpoint with these various frameworks, to make things easier, run the following commands to create an empty directory, create a package.json, install nodemon. create app.js file and finally add command to your package.json to start your app.js with nodemon.

mkdir myapi
cd myapi
npm init
npm install nodemon

Open your package.json, under your scripts

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start" : "nodemon app.js"
  },

Create an app.js file and you can run npm start from your command line. Create another folder and name it routes, inside the routes directory, create another js file and name it api.js. Now, we are ready!

1. Fastify

Fastify is a web framework highly focused on providing the best developer experience with the least overhead and a powerful plugin architecture. It is inspired by Hapi and Express and as far as we know, it is one of the fastest web frameworks in town.

To build an API endpoint with Fastify, first create a server and then create our API endpoint with Fastify. First, run npm install fastify

In your app.js, copy and paste the followings.

const fastify = require('fastify')({
    logger: true
  })
  
  fastify.register(require('./routes/api.js'))
  
  fastify.listen(5000, function (err, address) {
    if (err) {
      fastify.log.error(err)
      process.exit(1)
    }
    fastify.log.info(`server listening on ${address}`)
  })

In your routes/api.js, copy and paste the followings.

async function routes (fastify, options) {
    fastify.get('/', async (request, reply) => {
        return { home: 'home' }
      })
    
    fastify.get('/helloworld', async (request, reply) => {
      return { hello: 'world' }
    })

    fastify.get('/getUserData', async (request, reply) => {
        return { username: 'rasyue', email : 'rasyue@.com' }
    })
  }
  
  module.exports = routes

Run the server with npm start. Go to localhost:5000/getUserData on your browser.

fastify server running on port 3000

2. Koa

As usual, run npm install koa first and then copy and replace your app.js with the followings before running npm start

const Koa = require('koa');
const app = new Koa();

app.use(async ctx => {
  
  console.log(ctx.request);
  if(ctx.request.url == '/getUserData' ){

    ctx.body = JSON.stringify({username : 'rasyue', email : 'rasyue@gmail.com'})
  }else{
    ctx.body = 'Hello World';
  }
});

app.listen(5000);

The above code creates a basic Koa server that will return the response userData if you go to localhost:5000/getUserData.

koa-server

3. Express

Again, run npm install express, copy the followings and replace your app.js before running npm start

const express = require('express')
const app = express()
const port = 5000

app.get('/', (req, res) => res.send('Hello World!'))
app.get('/getUserData', (req, res) => res.send(JSON.stringify({username : 'rasyue', email : 'rasyue@gmail.com'})))

app.listen(port, () => console.log(`App is  listening port: ${port}`))

With this, you can make an API request from your front-end to the endpoint /getUserData to get the user-data. Pretty simple.

4. Hapi

Again, run npm install @hapi/hapi, copy the followings and replace your app.js before running npm start

'use strict';

const Hapi = require('@hapi/hapi');

const init = async () => {

    const server = Hapi.server({
        port: 5000,
        host: 'localhost'
    });

    server.route({
        method: 'GET',
        path: '/',
        handler: (request, h) => {

            return 'Hello World with Hapi';
        }
    });

    server.route({
        method: 'GET',
        path: '/getUserData',
        handler: (request, h) => {

            return JSON.stringify({username: 'rasyue', email : 'rasyue@gmail.com'});
        }
    });

    await server.start();
    console.log('Server running on port %s', server.info.uri);
};

process.on('unhandledRejection', (err) => {

    console.log(err);
    process.exit(1);
});

init();

Like usual, go to localhost:5000/getUserData to see it returns the user-data

5. Restify

Finally, to use Restify. Run npm install restify and replace your app.js with the followings before npm start

var restify = require('restify');

function respond(req, res, next) {
  res.send({username: req.params.name});
  next();
}

var server = restify.createServer();
server.get('/user/:name', respond);
server.head('/user/:name', respond);

server.listen(5000, function() {
  console.log('%s listening at %s', server.name, server.url);
});

There you have it, creating API endpoint using 5 different NodeJs frameworks.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

*
*