Tutorial Node.js: REST API (Calculator)
CRUD:
- Create — INSERT
- Read — SELECT
- Update — UPDATE
- Delete — DELETE
Begin with the usual, create a repository and a .json package:
For this one we will need to use hapi as a framework, that is used to create apps web.
For the index.js use:
//Framework hapi.js
const Hapi = require(‘hapi’);
// Máquina e Porto Lógico
const host = ‘localhost’;
const port = 3000;
// Criação do Servidor
const server = Hapi.Server({
host: host,
port: port
});
// Iniciar servidor
const init = async () => {
await server.start();
console.log(“Server up no porto: “ + port);
}
//Inicialização da App
init();
Everthing is set to start so: node index.js
Now we need to create routes for the app to be able to function as wanted.
Lets try this:
mkdir routes
cd routes
create file routes.js
Now back to the index.js file lets set the routes:
To update the routes file lets use the following code:
module.exports = function(server) {
//route About
server.route({
method: ‘GET’,
path: ‘/calculadora/about’,
handler: function (pedido){
var data = { msg: ‘API Calculadora’ };
return data;
}
});
//route Soma
server.route({
method: ‘GET’,
path: ‘/calculadora/soma/{num1}/{num2}’,
handler: function (pedido) {
const num1 = parseInt(pedido.params.num1);
const num2 = parseInt(pedido.params.num2);
var data = { resultado: num1 + num2 };
return data; }
});
//route Subtração server.route({
method: ‘GET’,
path: ‘/calculadora/sub/{num1}/{num2}’,
handler: function (pedido){
const num1 = parseInt(pedido.params.num1);
const num2 = parseInt(pedido.params.num2);
var data = { resultado: num1 — num2 };
return data; } });
//route Multiplicação server.route({
method: ‘GET’,
path: ‘/calculadora/multi/{num1}/{num2}’,
handler: function (pedido){ const num1 = parseInt(pedido.params.num1); const num2 = parseInt(pedido.params.num2);
var data = { resultado: num1 * num2 };
return data; }
});
//route Divisão server.route({
method: ‘GET’,
path: ‘/calculadora/div/{num1}/{num2}’,
handler: function (pedido){ const num1 = parseInt(pedido.params.num1); const num2 = parseInt(pedido.params.num2);
var data = { resultado: num1 / num2 }; return data; }
});
}