{"id":109,"date":"2019-12-20T22:27:53","date_gmt":"2019-12-20T22:27:53","guid":{"rendered":"https:\/\/www.kindsonthegenius.com\/nodejs\/?p=109"},"modified":"2022-03-09T08:48:11","modified_gmt":"2022-03-09T08:48:11","slug":"rest-api","status":"publish","type":"post","link":"https:\/\/kindsonthegenius.com\/nodejs\/rest-api\/","title":{"rendered":"Node.js &#8211; Create a REST API"},"content":{"rendered":"<p>You can use Node.js to build REST APIs very easily.<\/p>\n<p>In this tutorial, we would build a REST API for managing user details. Our API would be able too<\/p>\n<p>&nbsp;<\/p>\n<ol>\n<li><a href=\"#t1\">Create the JSON LIbrary<\/a><\/li>\n<li><a href=\"#t2\">Get list of users<\/a><\/li>\n<li><a href=\"#t3\">Insert a user<\/a><\/li>\n<li><a href=\"#t4\">Get a single user by Id<\/a><\/li>\n<li><a href=\"#t5\">Delete a user by Id<\/a><\/li>\n<\/ol>\n<p>&nbsp;<\/p>\n<h5><strong id=\"t1\">1. Create the JSON Library<\/strong><\/h5>\n<p>As you know, if you are going to manipulate data, you need some database. In out case, we would just use data file in a directory.<\/p>\n<p>The file containing list of users would be a json file named users.json.<\/p>\n<p>The users file contain four fields: id, firstname, lastname and email.<\/p>\n<p>The content of the user.json file is given below.<br \/>\n<!-- HTML generated using hilite.me --><\/p>\n<pre style=\"margin: 0; line-height: 125%;\">{\r\n  <span style=\"color: #007700;\">\"user1\"<\/span>: {\r\n    <span style=\"color: #007700;\">\"id\"<\/span>:<span style=\"color: #0000dd; font-weight: bold;\">1<\/span>,\r\n    <span style=\"color: #007700;\">\"firstname\"<\/span>:<span style=\"background-color: #fff0f0;\">\"Munonye\"<\/span>,\r\n    <span style=\"color: #007700;\">\"lastname\"<\/span>:<span style=\"background-color: #fff0f0;\">\"Kindson\"<\/span>,\r\n    <span style=\"color: #007700;\">\"email\"<\/span>:<span style=\"background-color: #fff0f0;\">\"kany@gmail.com\"<\/span>\r\n  },\r\n\r\n  <span style=\"color: #007700;\">\"user2\"<\/span>:  {\r\n    <span style=\"color: #007700;\">\"id\"<\/span>:<span style=\"color: #0000dd; font-weight: bold;\">2<\/span>,\r\n    <span style=\"color: #007700;\">\"firstname\"<\/span>:<span style=\"background-color: #fff0f0;\">\"Imolode\"<\/span>,\r\n    <span style=\"color: #007700;\">\"lastname\"<\/span>:<span style=\"background-color: #fff0f0;\">\"Saffron\"<\/span>,\r\n    <span style=\"color: #007700;\">\"email\"<\/span>:<span style=\"background-color: #fff0f0;\">\"saffron@gmail.com\"<\/span>\r\n  },\r\n\r\n  <span style=\"color: #007700;\">\"user3\"<\/span>:  {\r\n    <span style=\"color: #007700;\">\"id\"<\/span>:<span style=\"color: #0000dd; font-weight: bold;\">3<\/span>,\r\n    <span style=\"color: #007700;\">\"firstname\"<\/span>:<span style=\"background-color: #fff0f0;\">\"Munonye\"<\/span>,\r\n    <span style=\"color: #007700;\">\"lastname\"<\/span>:<span style=\"background-color: #fff0f0;\">\"Othniel\"<\/span>,\r\n    <span style=\"color: #007700;\">\"email\"<\/span>:<span style=\"background-color: #fff0f0;\">\"othniel@gmail.com\"<\/span>\r\n  },\r\n\r\n  <span style=\"color: #007700;\">\"user4\"<\/span>: {\r\n    <span style=\"color: #007700;\">\"id\"<\/span>:<span style=\"color: #0000dd; font-weight: bold;\">4<\/span>,\r\n    <span style=\"color: #007700;\">\"firstname\"<\/span>:<span style=\"background-color: #fff0f0;\">\"Yuba\"<\/span>,\r\n    <span style=\"color: #007700;\">\"lastname\"<\/span>:<span style=\"background-color: #fff0f0;\">\"Oleander\"<\/span>,\r\n    <span style=\"color: #007700;\">\"email\"<\/span>:<span style=\"background-color: #fff0f0;\">\"oleander@gmail.com\"<\/span>\r\n  }\r\n}\r\n<\/pre>\n<p>&nbsp;<\/p>\n<h5><strong id=\"t2\">2. Return a List of Users<\/strong><\/h5>\n<p>We would now create a REST API to return a list of users by reading the users.json file. We are going to use <a href=\"https:\/\/kindsonthegenius.com\/nodejs\/node-js-express-framework\/\">Express Framework<\/a>. You learnt this in the <a href=\"https:\/\/kindsonthegenius.com\/nodejs\/node-js-express-framework\/\">preceding section<\/a>.<\/p>\n<p>So create\u00a0 a file named server.js and place it in the same directory with the users.json file. The content of the server.js file is shown below:<\/p>\n<p>&nbsp;<\/p>\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #888888;\">\/\/REST API demo in Node.js<\/span>\r\n<span style=\"color: #008800; font-weight: bold;\">var<\/span> express <span style=\"color: #333333;\">=<\/span> require(<span style=\"background-color: #fff0f0;\">'express'<\/span>); <span style=\"color: #888888;\">\/\/ requre the express framework<\/span>\r\n<span style=\"color: #008800; font-weight: bold;\">var<\/span> app <span style=\"color: #333333;\">=<\/span> express();\r\n<span style=\"color: #008800; font-weight: bold;\">var<\/span> fs <span style=\"color: #333333;\">=<\/span> require(<span style=\"background-color: #fff0f0;\">'fs'<\/span>); <span style=\"color: #888888;\">\/\/require file system object<\/span>\r\n\r\n<span style=\"color: #888888;\">\/\/ Endpoint to Get a list of users<\/span>\r\napp.get(<span style=\"background-color: #fff0f0;\">'\/getUsers'<\/span>, <span style=\"color: #008800; font-weight: bold;\">function<\/span>(req, res){\r\n    fs.readFile(__dirname <span style=\"color: #333333;\">+<\/span> <span style=\"background-color: #fff0f0;\">\"\/\"<\/span> <span style=\"color: #333333;\">+<\/span> <span style=\"background-color: #fff0f0;\">\"users.json\"<\/span>, <span style=\"background-color: #fff0f0;\">'utf8'<\/span>, <span style=\"color: #008800; font-weight: bold;\">function<\/span>(err, data){\r\n        console.log(data);\r\n        res.end(data); <span style=\"color: #888888;\">\/\/ you can also use res.send()<\/span>\r\n    });\r\n})\r\n\r\n<span style=\"color: #888888;\">\/\/ Create a server to listen at port 8080<\/span>\r\n<span style=\"color: #008800; font-weight: bold;\">var<\/span> server <span style=\"color: #333333;\">=<\/span> app.listen(<span style=\"color: #0000dd; font-weight: bold;\">8080<\/span>, <span style=\"color: #008800; font-weight: bold;\">function<\/span>(){\r\n    <span style=\"color: #008800; font-weight: bold;\">var<\/span> host <span style=\"color: #333333;\">=<\/span> server.address().address\r\n    <span style=\"color: #008800; font-weight: bold;\">var<\/span> port <span style=\"color: #333333;\">=<\/span> server.address().port\r\n    console.log(<span style=\"background-color: #fff0f0;\">\"REST API demo app listening at http:\/\/%s:%s\"<\/span>, host, port)\r\n})\r\n<\/pre>\n<p>&nbsp;<\/p>\n<p>Now, run the program using the command<\/p>\n<pre style=\"margin: 0; line-height: 125%;\">Node server.js\r\n<\/pre>\n<p>Then open your browser and\u00a0 visit http:\/\/localhost:8080<\/p>\n<p>You will a list of users which is the content of the users.json file.<\/p>\n<p>&nbsp;<\/p>\n<h5><strong id=\"t3\">3. Inserting a New User<\/strong><\/h5>\n<p>We would now write the method to insert a new user. To achieve this, we would take three steps:<\/p>\n<ul>\n<li>read the existing users<\/li>\n<li>we would first create a user variable as json.<\/li>\n<li>append the user variable into the list<\/li>\n<\/ul>\n<p>I have written the code below to be added to the existing code. Here the endpoint to add a user is \/addUser<\/p>\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #888888;\">\/\/Step 1: Create a new user variable<\/span>\r\n<span style=\"color: #008800; font-weight: bold;\">var<\/span> user <span style=\"color: #333333;\">=<\/span> {\r\n    <span style=\"background-color: #fff0f0;\">\"user5\"<\/span><span style=\"color: #333333;\">:<\/span> {\r\n        <span style=\"background-color: #fff0f0;\">\"id\"<\/span><span style=\"color: #333333;\">:<\/span><span style=\"color: #0000dd; font-weight: bold;\">5<\/span>,\r\n        <span style=\"background-color: #fff0f0;\">\"firstname\"<\/span><span style=\"color: #333333;\">:<\/span><span style=\"background-color: #fff0f0;\">\"Liudmyla\"<\/span>,\r\n        <span style=\"background-color: #fff0f0;\">\"lastname\"<\/span><span style=\"color: #333333;\">:<\/span><span style=\"background-color: #fff0f0;\">\"Nagorna\"<\/span>,\r\n        <span style=\"background-color: #fff0f0;\">\"email\"<\/span><span style=\"color: #333333;\">:<\/span><span style=\"background-color: #fff0f0;\">\"mila@gmail.com\"<\/span>\r\n      },\r\n} \r\n\r\n<span style=\"color: #888888;\">\/\/The addUser endpoint<\/span>\r\napp.post(<span style=\"background-color: #fff0f0;\">'\/addUser'<\/span>, <span style=\"color: #008800; font-weight: bold;\">function<\/span>(req, res){\r\n    <span style=\"color: #888888;\">\/\/Step 2: read existing users<\/span>\r\n    fs.readFile(__dirname <span style=\"color: #333333;\">+<\/span> <span style=\"background-color: #fff0f0;\">\"\/\"<\/span> <span style=\"color: #333333;\">+<\/span> <span style=\"background-color: #fff0f0;\">\"users.json\"<\/span>, <span style=\"background-color: #fff0f0;\">'utf8'<\/span>, <span style=\"color: #008800; font-weight: bold;\">function<\/span>(err, data){\r\n        data <span style=\"color: #333333;\">=<\/span> JSON.parse(data);\r\n        <span style=\"color: #888888;\">\/\/Step 3: append user variable to list<\/span>\r\n        data[<span style=\"background-color: #fff0f0;\">\"user5\"<\/span>] <span style=\"color: #333333;\">=<\/span> user[<span style=\"background-color: #fff0f0;\">\"user5\"<\/span>];\r\n        console.log(data);\r\n        res.end(JSON.stringify(data));\r\n    });\r\n})\r\n<\/pre>\n<p>Now use a REST Client to make a post request to http:\/\/localhost:8080\/addUser<\/p>\n<p>You will get a response which is a list with the new user added. Learn <a href=\"https:\/\/www.youtube.com\/watch?v=KD36Yy9mMUE\" target=\"_blank\" rel=\"noopener\">how to use Advanced REST Client here<\/a>.<\/p>\n<p>&nbsp;<\/p>\n<h5><strong id=\"t4\">4. Get User by Id<\/strong><\/h5>\n<p>You can also get user by a particular id. So I&#8217;m going to just give you the code. Simply enter the code and then run it to see the output:<\/p>\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #888888;\">\/\/Endpoint to get a single user by id<\/span>\r\napp.get(<span style=\"background-color: #fff0f0;\">'\/:id'<\/span>, <span style=\"color: #008800; font-weight: bold;\">function<\/span> (req, res) {\r\n    <span style=\"color: #888888;\">\/\/ First retrieve existing user list<\/span>\r\n    fs.readFile( __dirname <span style=\"color: #333333;\">+<\/span> <span style=\"background-color: #fff0f0;\">\"\/\"<\/span> <span style=\"color: #333333;\">+<\/span> <span style=\"background-color: #fff0f0;\">\"users.json\"<\/span>, <span style=\"background-color: #fff0f0;\">'utf8'<\/span>, <span style=\"color: #008800; font-weight: bold;\">function<\/span> (err, data) {\r\n       <span style=\"color: #008800; font-weight: bold;\">var<\/span> users <span style=\"color: #333333;\">=<\/span> JSON.parse( data );\r\n       <span style=\"color: #008800; font-weight: bold;\">var<\/span> user <span style=\"color: #333333;\">=<\/span> users[<span style=\"background-color: #fff0f0;\">\"user\"<\/span> <span style=\"color: #333333;\">+<\/span> req.params.id] \r\n       console.log( user );\r\n       res.end( JSON.stringify(user));\r\n    });\r\n })\r\n<\/pre>\n<p>&nbsp;<\/p>\n<h5><strong id=\"t5\">5. Deleting a User By id<\/strong><\/h5>\n<p>We are now going to write the endpoint to delete a single user by id. The code is given below but note that you must access the url using a REST Client<\/p>\n<pre style=\"margin: 0; line-height: 125%;\"> <span style=\"color: #888888;\">\/\/Code to delete a user by id<\/span>\r\n <span style=\"color: #008800; font-weight: bold;\">var<\/span> id <span style=\"color: #333333;\">=<\/span> <span style=\"color: #0000dd; font-weight: bold;\">3<\/span>;\r\n app.<span style=\"color: #008800; font-weight: bold;\">delete<\/span>(<span style=\"background-color: #fff0f0;\">'\/deleteUser'<\/span>, <span style=\"color: #008800; font-weight: bold;\">function<\/span> (req, res) {\r\n    <span style=\"color: #888888;\">\/\/ First retrieve existing users<\/span>\r\n    fs.readFile( __dirname <span style=\"color: #333333;\">+<\/span> <span style=\"background-color: #fff0f0;\">\"\/\"<\/span> <span style=\"color: #333333;\">+<\/span> <span style=\"background-color: #fff0f0;\">\"users.json\"<\/span>, <span style=\"background-color: #fff0f0;\">'utf8'<\/span>, <span style=\"color: #008800; font-weight: bold;\">function<\/span> (err, data) {\r\n       data <span style=\"color: #333333;\">=<\/span> JSON.parse( data );\r\n       <span style=\"color: #008800; font-weight: bold;\">delete<\/span> data[<span style=\"background-color: #fff0f0;\">\"user\"<\/span> <span style=\"color: #333333;\">+<\/span> <span style=\"color: #0000dd; font-weight: bold;\">3<\/span>];\r\n        \r\n       console.log( data );\r\n       res.end( JSON.stringify(data));\r\n    });\r\n })\r\n<\/pre>\n<p>If you have come this far, thumbs up! In the next sections,we would see how we can achieve these using html forms.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>You can use Node.js to build REST APIs very easily. In this tutorial, we would build a REST API for managing user details. Our API &hellip; <\/p>\n","protected":false},"author":1,"featured_media":111,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_monsterinsights_skip_tracking":false,"footnotes":""},"categories":[2],"tags":[12,11],"class_list":["post-109","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-node-js-tutorials","tag-api","tag-rest-api"],"_links":{"self":[{"href":"https:\/\/kindsonthegenius.com\/nodejs\/wp-json\/wp\/v2\/posts\/109","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/kindsonthegenius.com\/nodejs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/kindsonthegenius.com\/nodejs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/kindsonthegenius.com\/nodejs\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/kindsonthegenius.com\/nodejs\/wp-json\/wp\/v2\/comments?post=109"}],"version-history":[{"count":4,"href":"https:\/\/kindsonthegenius.com\/nodejs\/wp-json\/wp\/v2\/posts\/109\/revisions"}],"predecessor-version":[{"id":265,"href":"https:\/\/kindsonthegenius.com\/nodejs\/wp-json\/wp\/v2\/posts\/109\/revisions\/265"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/kindsonthegenius.com\/nodejs\/wp-json\/wp\/v2\/media\/111"}],"wp:attachment":[{"href":"https:\/\/kindsonthegenius.com\/nodejs\/wp-json\/wp\/v2\/media?parent=109"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/kindsonthegenius.com\/nodejs\/wp-json\/wp\/v2\/categories?post=109"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/kindsonthegenius.com\/nodejs\/wp-json\/wp\/v2\/tags?post=109"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}