{"id":198,"date":"2022-01-09T09:50:05","date_gmt":"2022-01-09T09:50:05","guid":{"rendered":"http:\/\/frontendguruji.com\/?p=198"},"modified":"2022-01-09T19:20:29","modified_gmt":"2022-01-09T19:20:29","slug":"how-to-create-api-in-nodejs-without-express-js","status":"publish","type":"post","link":"https:\/\/frontendguruji.com\/blog\/how-to-create-api-in-nodejs-without-express-js\/","title":{"rendered":"How to create API in NodeJS without Express JS"},"content":{"rendered":"\n<p>Hello Friends &#x1f64f;, here I am with another &#x1f525; topic, how to <strong>create API in NodeJS without Express<\/strong> &#x1f62e;&#x1f601;.<gwmw style=\"display:none;\"><\/p>\n\n\n\n<p>Whenever we have to create API in Node, first thing we do is &#x1f60e;<strong> install Express JS<\/strong>, right!. Because it&#8217;s easy to write!, but under the hood it is using Node JS only, its just a wrapper.<\/p>\n\n\n\n<p>Today in this <strong>Node JS Tutorial<\/strong>, we will <strong>create API in NodeJS without Express<\/strong>, will <strong>create POST &amp; GET API<\/strong> and will learn <strong>how to use Postman to test API<\/strong>.&#x1f44d;.<\/p>\n\n\n\n<p><strong>Chalo suru kiya jaye!<\/strong>&#x1f37b;<strong>&nbsp;Lets start!&nbsp;<\/strong>&#x1f57a;.<\/p>\n\n\n\n<h2>Step 1: Install\/Upgrade\/Verify Node &amp; Postman<\/h2>\n\n\n\n<p>To start with the setup, please verify if your machine has node. If not, then\u00a0<a rel=\"noreferrer noopener\" href=\"https:\/\/nodejs.org\/en\/\" target=\"_blank\">install node package here<\/a>.<\/p>\n\n\n\n<p>While upgrading node package on my machine to the latest version: 16.13.1 which includes npm 8.1.2, I faced one issue, maybe you also get this type of error, check here to resolve it:&nbsp;<a rel=\"noreferrer noopener\" href=\"http:\/\/frontendguruji.com\/warn-npm-does-not-support-node-js-v16-13-1\/\" target=\"_blank\">WARN npm does not support Node.js v16.13.1<\/a><\/p>\n\n\n\n<p>Another tool you will need is <strong><a href=\"https:\/\/www.postman.com\/downloads\/\" target=\"_blank\" rel=\"noreferrer noopener\">Postman<\/a><\/strong>, this is needed <strong>to test API<\/strong>, as we are not developing front-end for now.<gwmw style=\"display:none;\"><\/gwmw><\/p>\n\n\n\n<h2>Step 2: Initialize a folder<gwmw style=\"display:none;\"><\/gwmw><\/h2>\n\n\n\n<p>So friends! first thing we have to do is to create a blank folder&nbsp;&#x1f4c1;&nbsp;&amp; initialize it using below command<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>npm init<\/code><\/pre>\n\n\n\n<p>This command will run a wizard of questions\/choices related to the project &amp; we have to answer\/select them. This basically creates a&nbsp;<strong>package.json<\/strong>&nbsp;file which will include all our answers\/selections.<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img width=\"823\" height=\"662\" src=\"http:\/\/frontendguruji.com\/wp-content\/uploads\/2022\/01\/image-5.png\" alt=\"node js,create api in nodejs without express,create post api in nodejs,create get api in nodejs,how to use postman to test api,nodejs tutorial\" class=\"wp-image-201\" srcset=\"https:\/\/frontendguruji.com\/blog\/wp-content\/uploads\/2022\/01\/image-5.png 823w, https:\/\/frontendguruji.com\/blog\/wp-content\/uploads\/2022\/01\/image-5-300x241.png 300w, https:\/\/frontendguruji.com\/blog\/wp-content\/uploads\/2022\/01\/image-5-768x618.png 768w\" sizes=\"(max-width: 823px) 100vw, 823px\" \/><\/figure>\n\n\n\n<h2>Step 3: Server Setup<\/h2>\n\n\n\n<p>Create <strong>server.js<\/strong> file, this will contain the code related to initialization of the server.<\/p>\n\n\n\n<p>First import NodeJS <strong>http module<\/strong>, this <strong>allows NodeJS to transfer data over HTTP<\/strong> (Hyper Text Transfer Protocol).<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><strong>\/\/ server.js file<\/strong>\nconst http = require(\"<strong>http<\/strong>\");<\/code><\/pre>\n\n\n\n<p>Now we can create the server using http <strong>createServer <\/strong>method. It has two parameters:<br><strong>request<\/strong>: this contains request Object from client<br><strong>response<\/strong>: this contains response Object for client<\/p>\n\n\n\n<p>Here we are just returning a string in response for client, so have used <strong>&#8220;Content-type&#8221;: &#8220;text\/plain&#8221;<\/strong>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>const server = http.<strong>createServer<\/strong>((<strong>request<\/strong>, <strong>response<\/strong>) =&gt; {\n  response.writeHead(200, { \"Content-Type\": \"text\/plain\" });\n  response.write(\"Hello World!\");\n  response.end();\n});<\/code><\/pre>\n\n\n\n<p>Now lets bind this server to a <strong>port<\/strong>, so that server can receive requests. For this, we need to add a <strong>listener<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>server.<strong>listen<\/strong>(<strong>9000<\/strong>, () =&gt; {\n  console.log(\"Server is running on Port 9000\");\n});<\/code><\/pre>\n\n\n\n<p>That&#8217;s all, now to run the server open terminal\/cmd prompt and run below command, this will run the server and start listening on port 9000.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>node server.js<\/code><\/pre>\n\n\n\n<figure class=\"wp-block-image size-full\"><img width=\"670\" height=\"49\" src=\"http:\/\/frontendguruji.com\/wp-content\/uploads\/2022\/01\/image-6.png\" alt=\"node js,create api in nodejs without express,create post api in nodejs,create get api in nodejs,how to use postman to test api,nodejs tutorial\" class=\"wp-image-202\" srcset=\"https:\/\/frontendguruji.com\/blog\/wp-content\/uploads\/2022\/01\/image-6.png 670w, https:\/\/frontendguruji.com\/blog\/wp-content\/uploads\/2022\/01\/image-6-300x22.png 300w\" sizes=\"(max-width: 670px) 100vw, 670px\" \/><\/figure>\n\n\n\n<h2>Step 4: Use Postman to test API<gwmw style=\"display:none;\"><\/h2>\n\n\n\n<p>Open Postman, enter the URL and click on Send button.<br>This will return the default mesage<strong> &#8220;Hello World!&#8221;<\/strong> from the server. &#x1f44f;<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img width=\"1024\" height=\"498\" src=\"http:\/\/frontendguruji.com\/wp-content\/uploads\/2022\/01\/image-8-1024x498.png\" alt=\"node js,create api in nodejs without express,create post api in nodejs,create get api in nodejs,how to use postman to test api,nodejs tutorial\" class=\"wp-image-205\" srcset=\"https:\/\/frontendguruji.com\/blog\/wp-content\/uploads\/2022\/01\/image-8-1024x498.png 1024w, https:\/\/frontendguruji.com\/blog\/wp-content\/uploads\/2022\/01\/image-8-300x146.png 300w, https:\/\/frontendguruji.com\/blog\/wp-content\/uploads\/2022\/01\/image-8-768x373.png 768w, https:\/\/frontendguruji.com\/blog\/wp-content\/uploads\/2022\/01\/image-8.png 1049w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n\n\n\n<p>In this setup, server will return same message every time we hit URL from the Postman. And nothing will change if you make POST or a GET method.<\/p>\n\n\n\n<h2>Step 5: Server Setup for POST &amp; GET API<\/h2>\n\n\n\n<p>Now to make this server setup ready for creating POST and GET API, we need to modify our <strong>server.js<\/strong> code, and instead of directly returning a response, we will check the method type and based on that, will code the logic (in <strong>controller.js<\/strong>).<\/p>\n\n\n\n<p>Here we are fetching <strong>URL <\/strong>and <strong>Method type<\/strong> from the <strong>request <\/strong>parameter. And the switch statement depends upon the Method Type. We will be coding logic for each method type in next steps.<br>But first we have to declare <strong>default case<\/strong>, so that whenever we hit NodeJS server using <strong>Postman <\/strong>and if no case matches, then by default it will return &#8220;<strong>API not found<\/strong>&#8221; message.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><strong>\/\/ Update the Server Code<\/strong>\nconst server = http.createServer((request, response) =&gt; {\n  const <strong>reqURL <\/strong>= request.url;\n  const <strong>reqMethod <\/strong>= request.method;\n  switch (<strong>reqMethod<\/strong>) {\n    <strong>default<\/strong>: {\n      <strong>defaultHandler<\/strong>(resquest, response)\n    }\n  }\n});<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code><strong>\/\/ add <\/strong>defaultHandler <strong>method in controller.js<\/strong>\nconst <strong>defaultHandler <\/strong>= (request, response) => {\r\n  response.writeHead(200, {\r\n    \"Content-Type\": \"application\/json\",\r\n  });\r\n  response.write(\r\n    JSON.stringify({\r\n      message: <strong>`API not found at ${request.url}`<\/strong>,\r\n    })\r\n  );\r\n  response.end();\r\n};<\/code><\/pre>\n\n\n\n<p> Now again access the API from postman and check the response. <\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img width=\"1024\" height=\"541\" src=\"http:\/\/frontendguruji.com\/wp-content\/uploads\/2022\/01\/image-10-1024x541.png\" alt=\"node js,create api in nodejs without express,create post api in nodejs,create get api in nodejs,how to use postman to test api,nodejs tutorial\" class=\"wp-image-207\" srcset=\"https:\/\/frontendguruji.com\/blog\/wp-content\/uploads\/2022\/01\/image-10-1024x541.png 1024w, https:\/\/frontendguruji.com\/blog\/wp-content\/uploads\/2022\/01\/image-10-300x159.png 300w, https:\/\/frontendguruji.com\/blog\/wp-content\/uploads\/2022\/01\/image-10-768x406.png 768w, https:\/\/frontendguruji.com\/blog\/wp-content\/uploads\/2022\/01\/image-10.png 1048w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n\n\n\n<h3>Create POST API in NodeJS<\/h3>\n\n\n\n<p>HTTP<strong> POST method<\/strong> is required to send data in the body of the API to the server. <br>As we will be sending data from Postman, this API must be able to read the data. <br>API name: <strong>post-api<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><strong>\/\/<\/strong> <strong>add <\/strong>POST <strong>case to the switch statement<\/strong> <strong>in server.js<\/strong>\ncase \"<strong>POST<\/strong>\": {\n  if (reqURL === \"<strong>\/post-api<\/strong>\") {\n   <strong>postHandler<\/strong>(request, response);\n  }\n  break;\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code><strong>\/\/ add <\/strong>postHandler <strong>method in controller.js<\/strong>\nexport const <strong>postHandler<\/strong> = (request, response) =&gt; {\n  \/\/read the data from request\n  response.writeHead(200, {\n    \"Content-Type\": \"application\/json\"\n  });\n  response.write(JSON.stringify({\n    message: \"POST Successful\"\n  }));\n  response.end()\n}<\/code><\/pre>\n\n\n\n<p>Now we have to parse the POST request body. In ExpressJS we use <strong>body-parser<\/strong> for the same.<br>But here we are using custom code, it will act as a body-parser to read the POST data. <br>I have created an another tutorial on this custom body parser, check here: <strong><a href=\"http:\/\/frontendguruji.com\/how-to-parse-post-request-in-node-js-without-expressjs-body-parser\/\">How to parse the POST request body in NodeJS without using ExpressJS body-parser<\/a><\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><strong>\/\/ update the postHandler with custom body parser code<\/strong>\nconst <strong>postHandler <\/strong>= (request, response) => {\n\n<span style=\"color:#a39200\" class=\"has-inline-color\">  <strong>let chunks = &#91;];\n  request.on(\"data\", (chunk) => {\n    chunks.push(chunk);\n  });\n  request.on(\"end\", () => {<\/strong>\n    <strong>const data = Buffer.concat(chunks);\n    const parsedData = qs.parse(data.toString());\n    console.log(parsedData);\n    \/\/ Now request data is accessible using parsedData\n    \/\/ And we can do any operation on the same, like saving it to databse<\/strong><\/span>\n\n    \/\/return the success response\n    response.writeHead(200, {\n      \"Content-Type\": \"application\/json\",\n    });\n    response.write(\n      JSON.stringify({\n        message: \"POST Succesfull\",\n      })\n    );\n    response.end();\n  <strong>});<\/strong>\n};<\/code><\/pre>\n\n\n\n<p>Now we can hit  <strong>\/post-api<\/strong> from Postman with some data.<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img width=\"713\" height=\"416\" src=\"http:\/\/frontendguruji.com\/wp-content\/uploads\/2022\/01\/image-23.png\" alt=\"node js,create api in nodejs without express,create post api in nodejs,create get api in nodejs,how to use postman to test api,nodejs tutorial\" class=\"wp-image-409\" srcset=\"https:\/\/frontendguruji.com\/blog\/wp-content\/uploads\/2022\/01\/image-23.png 713w, https:\/\/frontendguruji.com\/blog\/wp-content\/uploads\/2022\/01\/image-23-300x175.png 300w, https:\/\/frontendguruji.com\/blog\/wp-content\/uploads\/2022\/01\/image-23-150x88.png 150w\" sizes=\"(max-width: 713px) 100vw, 713px\" \/><\/figure>\n\n\n\n<p>At server we will receive data as:<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img width=\"479\" height=\"107\" src=\"http:\/\/frontendguruji.com\/wp-content\/uploads\/2022\/01\/image-22.png\" alt=\"node js,create api in nodejs without express,create post api in nodejs,create get api in nodejs,how to use postman to test api,nodejs tutorial\" class=\"wp-image-407\" srcset=\"https:\/\/frontendguruji.com\/blog\/wp-content\/uploads\/2022\/01\/image-22.png 479w, https:\/\/frontendguruji.com\/blog\/wp-content\/uploads\/2022\/01\/image-22-300x67.png 300w, https:\/\/frontendguruji.com\/blog\/wp-content\/uploads\/2022\/01\/image-22-150x34.png 150w\" sizes=\"(max-width: 479px) 100vw, 479px\" \/><\/figure>\n\n\n\n<h3> Create GET API in NodeJS<\/h3>\n\n\n\n<p>HTTP<strong> GET method<\/strong> is required if we just want to request data and there is nothing to send. We can send, but in the form of querystring in the URL not in the body of the API.  <br>API name: <strong>get-api<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><strong>\/\/<\/strong> <strong>add GET case to the switch statement<\/strong> <strong>in server.js<\/strong>\ncase \"GET\": {\n  if (reqURL === \"<strong>\/get-api<\/strong>\") {\n   <strong>getHandler<\/strong>();\n  }\n  break;\n}<\/code><\/pre>\n\n\n\n<p>Below in the controller, I have created a custom data Object, this will go back in response.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><strong>\/\/ add <\/strong>getHandler <strong>method in controller.js<\/strong>\nconst <strong>getHandler <\/strong>= (request, response) => {\n  const data = <strong>{\n    name: \"frontendguruji\",\n    category: \"technology\",\n    website: \"frontendguruji.com\",\n  }<\/strong>;\n  response.writeHead(200, {\n    \"Content-Type\": \"application\/json\",\n  });\n  response.write(\n    JSON.stringify({\n      message: \"GET Succesfull\",\n      <strong>data<\/strong>,\n    })\n  );\n  response.end();\n};<\/code><\/pre>\n\n\n\n<p>Now we can hit  <strong>\/get-api<\/strong> from Postman. Here we will receive the above custom data back in response from server.<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img width=\"655\" height=\"540\" src=\"http:\/\/frontendguruji.com\/wp-content\/uploads\/2022\/01\/image-24.png\" alt=\"node js,create api in nodejs without express,create post api in nodejs,create get api in nodejs,how to use postman to test api,nodejs tutorial\" class=\"wp-image-410\" srcset=\"https:\/\/frontendguruji.com\/blog\/wp-content\/uploads\/2022\/01\/image-24.png 655w, https:\/\/frontendguruji.com\/blog\/wp-content\/uploads\/2022\/01\/image-24-300x247.png 300w, https:\/\/frontendguruji.com\/blog\/wp-content\/uploads\/2022\/01\/image-24-150x124.png 150w\" sizes=\"(max-width: 655px) 100vw, 655px\" \/><\/figure>\n\n\n\n<p><strong><a href=\"https:\/\/github.com\/mandeeppasbola\/create-nodejs-rest-api-without-express\" target=\"_blank\" rel=\"noreferrer noopener\">Checkout the project here.<\/a><\/strong><\/p>\n\n\n\n<p>Thats all in this\u00a0<strong>NodeJS tutorial<\/strong>, here we learned how to\u00a0<strong>create API in NodeJS without Express JS<\/strong> by <strong>setting up the server<\/strong>, <strong>implementing POST &amp; GET API <\/strong>and learned <strong>how to use Postman to test API<\/strong>. <br>If you have any question or suggestion, please feel free to comment.<\/p>\n\n\n\n<p>Thanks &#x1f64f;.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this Node JS tutorial, learn how to create API in NodeJS without Express JS, how to implement POST &#038; GET API and how to use Postman for API testing.<\/p>\n","protected":false},"author":1,"featured_media":413,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"site-sidebar-layout":"default","site-content-layout":"default","ast-global-header-display":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","theme-transparent-header-meta":"","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":""},"categories":[28],"tags":[29,7,27,76,50],"_links":{"self":[{"href":"https:\/\/frontendguruji.com\/blog\/wp-json\/wp\/v2\/posts\/198"}],"collection":[{"href":"https:\/\/frontendguruji.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/frontendguruji.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/frontendguruji.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/frontendguruji.com\/blog\/wp-json\/wp\/v2\/comments?post=198"}],"version-history":[{"count":0,"href":"https:\/\/frontendguruji.com\/blog\/wp-json\/wp\/v2\/posts\/198\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/frontendguruji.com\/blog\/wp-json\/wp\/v2\/media\/413"}],"wp:attachment":[{"href":"https:\/\/frontendguruji.com\/blog\/wp-json\/wp\/v2\/media?parent=198"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/frontendguruji.com\/blog\/wp-json\/wp\/v2\/categories?post=198"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/frontendguruji.com\/blog\/wp-json\/wp\/v2\/tags?post=198"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}