Latest news about Bitcoin and all cryptocurrencies. Your daily crypto news habit.
NodeJS is most commonly used with Express framework. Also a bunch of other external libraries are used with NodeJS.
The Reason these frameworks and libraries are used along with NodeJS is to make development much more easier and quicker.
While working on any real project, it is best to use frameworks and libraries wherever needed to enable quicker development đ
That said, in this post I will be showing how to build Simple REST APIâs with NodeJS without using express framework or any other external libraries. This article will use only those functionalities that are provided with NodeJSÂ itself.
The reason for this is to show how NodeJS can be used without frameworks and libraries as well đ. Also this will give a better idea as to how NodeJS works đ
Pre-requisite
Install NodeJS from https://nodejs.org
Code
The code for this article is available in my github repo.
Letâs get started with the code đ
Create a folder called as simple-rest-apis-nodejs-without-frameworks. This will be our NodeJS Project folder.
Go into the project folder and use npm init to make the project into a node project. The commands to do this are
cd simple-rest-apis-nodejs-without-frameworksnpm init
package.json
After running npm init a package.json file is created within the project folder.
package.json has information about your project like project name, version, description etc. Also package.json is where you will be adding node dependencies. In this article we wonât be having any dependencies since we are using only functionalities that are provided by NodeJSÂ itself.
First API
Create a file called server.js inside the project folder. This will be the starting point of our application.
Copy the following code into server.js
const hostname = '127.0.0.1';const port = 3000;
const server = require('./controller.js');
server.listen(port, hostname, () => { console.log(`Server running at http://${hostname}:${port}/`);});
This code actually relies on a file called as controller.js which we will be adding soon. This code is telling that a server needs to listen on port 3000 and in localhost
The server creation is done in controller.js
controller.js
This is the file where we will be creating the server and defining our rest endpoints. Create a file called as controller.js
Letâs create a single GET endpoint first in controller.js
const http = require('http');const url = require('url');
module.exports = http.createServer((req, res) => {
var service = require('./service.js');const reqUrl = url.parse(req.url, true);
// GET Endpointif (reqUrl.pathname == '/sample' && req.method === 'GET') { console.log('Request Type:' + req.method + ' Endpoint: ' + reqUrl.pathname);
service.sampleRequest(req, res); } });
First http and url modules are imported. These modules are provided by NodeJSÂ itself.
http module enables to create web applications. It supports both client and server operations.
url module helps in parsing urls
The line http.createServer((req, res) => { indicates that a http server needs to be created with request as req and response as res
module.exports is used to export this file as a module. This is why we could import controller.js in server.js using const server = require('./controller.js');
It can be seen that this file requires service.js which we will talk about later.
The code const reqUrl = url.parse(req.url, true); gets the request url and parses it so that we can run some url functions on it.
The First endpoint we are going to create is a GET endpoint with endpoint url as /sample
In order to do url routing we will be using if else conditions
The line if (reqUrl.pathname == '/sample' && req.method === 'GET') { checks if the url being requested is /sample and also checks if the request type is GET
The logic for this get request is present in service.sampleRequest(req, res); which is a function defined in service.js
service.js
This is where the actual api logic will be present. Create a file called as service.js.
Copy the following code into service.js
const url = require('url');
exports.sampleRequest = function (req, res) {const reqUrl = url.parse(req.url, true);var name = 'World';if (reqUrl.query.name) { name = reqUrl.query.name }
var response = { "text": "Hello " + name };
res.statusCode = 200; res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify(response));};
This code checks if the request URL has a query parameter called as name and stores it in name variable. If no query parameter is present, it defaults to the string World
The response status is set as 200, Content Type of the response is JSON and finally the response is sent back using res.end(JSON.stringify(response));
since response variable is a JSON Object, we are using JSON.stringify on it to convert it to string before sending back the http response
Now we can run the application using the command
node server.js
Testing
In order to test the endpoint use postman. You can download it from here
In postman select Get request and type the url as http://localhost:3000/sample?name=aditya and hit send
The output for this request is shown below
{ "text": "Hello aditya"}
Now type the url as http://localhost:3000/sample and hit send
The output for this request is shown below
{ "text": "Hello World"}
Second API
In this section we will be building the second API which is a POST request. Also if user hits some random url, we will need to indicate that it is an invalid route. We will add the logic for that as well here.
controller.js
Update the code in controller.js to the one shown below
const http = require('http');const url = require('url');
module.exports = http.createServer((req, res) => {
var service = require('./service.js');const reqUrl = url.parse(req.url, true);
// GET Endpointif (reqUrl.pathname == '/sample' && req.method === 'GET') { console.log('Request Type:' + req.method + ' Endpoint: ' + reqUrl.pathname);
service.sampleRequest(req, res);
// POST Endpoint } else if (reqUrl.pathname == '/test' && req.method === 'POST') { console.log('Request Type:' + req.method + ' Endpoint: ' + reqUrl.pathname);
service.testRequest(req, res);
} else { console.log('Request Type:' + req.method + ' Invalid Endpoint: ' + reqUrl.pathname);
service.invalidRequest(req, res);
}});
Disclaimer
The views and opinions expressed in this article are solely those of the authors and do not reflect the views of Bitcoin Insider. Every investment and trading move involves risk - this is especially true for cryptocurrencies given their volatility. We strongly advise our readers to conduct their own research when making a decision.