Build REST APIs with Node.js and Hapi.js

Building a RESTful API is a common task in web development, as it allows client-side applications to interact with server-side data. In this tutorial, we will guide you through the process of building a RESTful API using Node.js and Hapi.js, a rich framework for building applications and services.

Setting Up Your Environment

Before we begin, ensure that you have Node.js installed on your machine. If not, you can download it from the official Node.js website. You’ll also need to install Hapi.js, which can be done using npm (Node Package Manager), a package manager for Node.js:

npm install @hapi/hapi

Creating a Hapi.js Server

First, let’s create a new Hapi.js server. Create a new file named server.js and add the following code:

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

const init = async () => {
    const server = Hapi.server({
        port: 3000,
        host: 'localhost'
    });

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

process.on('unhandledRejection', (err) => {
    console.log(err);
    process.exit(1);
});

init();

In this code, we’re creating a new Hapi.js server that listens on port 3000. The init function is used to start the server.

Creating the API Endpoints

Now, let’s create our API endpoints. We’ll create four endpoints for creating, reading, updating, and deleting resources:

server.route({
    method: 'POST',
    path: '/resources',
    handler: (request, h) => {
        // Code to create a resource...
    }
});

server.route({
    method: 'GET',
    path: '/resources',
    handler: (request, h) => {
        // Code to get all resources...
    }
});

server.route({
    method: 'GET',
    path: '/resources/{id}',
    handler: (request, h) => {
        // Code to get a resource by id...
    }
});

server.route({
    method: 'PUT',
    path: '/resources/{id}',
    handler: (request, h) => {
        // Code to update a resource...
    }
});

server.route({
    method: 'DELETE',
    path: '/resources/{id}',
    handler: (request, h) => {
        // Code to delete a resource...
    }
});

In each of these routes, we’re defining a method (POST, GET, PUT, DELETE), a path, and a handler function. The handler function is where you’ll write the code to interact with your data.

Conclusion

Building a RESTful API using Node.js and Hapi.js is a straightforward process. By understanding how to set up a Hapi.js server and define routes, you can create a wide range of APIs to suit your needs. Remember to always sanitize and validate your input data, handle errors appropriately, and secure your API to protect your data. Happy coding!

Facebook
Twitter
LinkedIn
Pinterest

Table of Contents

Related posts