Hapi.js is a powerful and flexible framework for building web applications and RESTful APIs in Node.js. It is known for its configuration-centric approach and extensibility. Below are the steps to get started with building RESTful APIs using Hapi.js:
Install Hapi.js: You can install Hapi.js using npm, the Node.js package manager. Open a terminal and run the following command:
bashnpm install hapi
Create a new Hapi.js project: Create a new directory for your project and navigate into it:
bashmkdir my-hapi-api
cd my-hapi-api
Initialize your project:
Run the following command to create a package.json
file:
bashnpm init -y
Create the main file (e.g., app.js
):
Create a new JavaScript file (e.g., app.js
) to serve as the entry point for your Hapi.js application.
javascriptconst Hapi = require('@hapi/hapi');
const init = async () => {
const server = Hapi.server({
port: 3000,
host: 'localhost',
});
server.route({
method: 'GET',
path: '/',
handler: (request, h) => {
return 'Hello, Hapi!';
},
});
await server.start();
console.log('Server running on %s', server.info.uri);
};
process.on('unhandledRejection', (err) => {
console.log(err);
process.exit(1);
});
init();
Run your Hapi.js server: Execute the following command to start your Hapi.js server:
bashnode app.js
You should see the message "Server running on http://localhost:3000" in the console.
Define routes for your RESTful API:
Expand your app.js
file to include routes for your API. For example:
javascript// ... (previous code)
server.route({
method: 'GET',
path: '/api/users',
handler: (request, h) => {
// Fetch and return a list of users
return [
{ id: 1, name: 'John Doe' },
{ id: 2, name: 'Jane Doe' },
];
},
});
// ... (additional routes)
// ...
Handling request parameters:
You can access request parameters using request.params
or request.query
:
javascriptserver.route({
method: 'GET',
path: '/api/users/{userId}',
handler: (request, h) => {
const userId = request.params.userId;
// Fetch and return user details for the specified userId
},
});
Additionally, you can use request payload for POST requests:
javascriptserver.route({
method: 'POST',
path: '/api/users',
handler: (request, h) => {
const newUser = request.payload;
// Process and save the new user
},
});
Middleware and plugins:
Hapi.js allows you to use middleware and plugins for additional functionality. You can use server.ext
to add extensions:
javascriptserver.ext('onRequest', (request, h) => {
// Your middleware logic here
return h.continue;
});
Validation and Joi: Hapi.js integrates with the Joi validation library. You can use Joi to validate request payloads, parameters, and query parameters:
javascriptconst Joi = require('joi');
server.route({
method: 'POST',
path: '/api/users',
handler: (request, h) => {
const newUser = request.payload;
// Process and save the new user
return 'User created successfully';
},
options: {
validate: {
payload: Joi.object({
name: Joi.string().required(),
email: Joi.string().email().required(),
}),
},
},
});
Handle errors: You can handle errors by returning a Boom response or throwing an error within your route handler:
javascriptserver.route({
method: 'GET',
path: '/api/error',
handler: (request, h) => {
// Example of handling an error
const error = Boom.badRequest('Custom error message');
throw error;
},
});
These steps should help you get started with building RESTful APIs using Hapi.js. Remember to refer to the official Hapi.js documentation for more detailed information on features and configuration options.