is most commonly used with Express framework. Also a bunch of other external libraries are used with NodeJS. NodeJS The Reason these and libraries are used along with NodeJS is to make development much more easier and quicker. frameworks 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 . This will be our NodeJS Project folder. simple-rest-apis-nodejs-without-frameworks Go into the project folder and use to make the project into a node project. The commands to do this are npm init cd simple-rest-apis-nodejs-without-frameworksnpm init package.json After running a file is created within the project folder. npm init package.json 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 inside the project folder. This will be the starting point of our application. server.js 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 which we will be adding soon. This code is telling that a server needs to listen on and in controller.js port 3000 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 Endpoint if (reqUrl.pathname == '/sample' && req.method === 'GET') { console.log('Request Type:' + req.method + ' Endpoint: ' + reqUrl.pathname); service.sampleRequest(req, res); } }); First and modules are imported. These modules are provided by NodeJS itself. http url module enables to create web applications. It supports both client and server operations. http module helps in parsing urls url The line indicates that a http server needs to be created with http.createServer((req, res) => { request as req and response as res is used to export this file as a module. This is why we could import in using module.exports controller.js server.js const server = require('./controller.js'); It can be seen that this file requires which we will talk about later. service.js The code gets the request url and parses it so that we can run some url functions on it. const reqUrl = url.parse(req.url, true); The First endpoint we are going to create is a endpoint with endpoint url as GET /sample In order to do url routing we will be using if else conditions The line checks if the url being requested is and also checks if the request type is if (reqUrl.pathname == '/sample' && req.method === 'GET') { /sample GET The logic for this get request is present in which is a function defined in service.sampleRequest(req, res); 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 and stores it in name variable. If no query parameter is present, it defaults to the string name World The response status is set as , Content Type of the response is and finally the response is sent back using 200 JSON res.end(JSON.stringify(response)); since is a JSON Object, we are using on it to convert it to string before sending back the http response response variable JSON.stringify Now we can run the application using the command node server.js Testing In order to test the endpoint use . You can download it from postman here In postman select Get request and type the url as and hit send http://localhost:3000/sample?name=aditya The output for this request is shown below { "text": "Hello aditya"} Now type the url as and hit send http://localhost:3000/sample 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 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. POST controller.js Update the code in to the one shown below 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 Endpoint if (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); }}); The post endpoint will have the url . This code has a condition to check for endpoint. The logic for endpoint will be in which is in /test /test /test service.testRequest(req, res); service.js This code also has an else condition for invalid routes. The logic for invalid routes is handled in service.invalidRequest(req, res); service.js Add the following piece of code to . Do not delete the existing code in service.js. Add this code below the existing code. service.js exports.testRequest = function (req, res) { body = ''; req.on('data', function (chunk) { body += chunk; }); req.on('end', function () { postBody = JSON.parse(body); var response = { "text": "Post Request Value is " + postBody.value }; res.statusCode = 200; res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify(response)); });}; For a POST request, an input POST body is given when the endpoint is called. In the code we will need to get this POST body from the request. The following code does this req.on('data', function (chunk) { body += chunk;}); The request comes in the form of a . This code takes the stream of data and keeps appending it to . stream body is executed only after the streaming is complete and the full is received. req.on('end', function () { post body This code converts the input post body into JSON format so that we can use the values in it. postBody = JSON.parse(body); in the code we are using field in the . value postBody The response is set similar to how we did it for GET request. logic for invalid request Add the following piece of code to . Do not delete the existing code in service.js. Add this code below the existing code. service.js exports.invalidRequest = function (req, res) { res.statusCode = 404; res.setHeader('Content-Type', 'text/plain'); res.end('Invalid Request');}; For an invalid request, the status is set to and content type is set to . The actual content sent back is 404 text Invalid Request Testing Go to postman. Select the request Type as and type the following url POST [http://localhost:3000/test](http://localhost:3000/test.) . Also select , and as shown in the image Body raw application/json The input Post body is given below { "value" : "nodejs"} Click on send in postman The API output is given below { "text": "Post Request Value is nodejs"} You can also try with an Invalid request. In postman select and type the url as GET [http://localhost:3000/test123](http://localhost:3000/test123) The response for this will be Invalid Text Congrats 😄 You now know how to create REST API’s in NodeJS without using any framework or external library 😄 In Real Projects always use a framework or library wherever possible to make dev cycle easier and quicker About the author I love technology and follow the advancements in the field. I also like helping others with my technology knowledge. Feel free to connect with me on my LinkedIn account https://www.linkedin.com/in/aditya1811/ You can also follow me on twitter https://twitter.com/adityasridhar18 My Website: https://adityasridhar.com/ Other Posts by Me An introduction to Git How to use Git efficiently How did that weird bug come in the code Originally published at adityasridhar.com .