{"id":268,"date":"2022-03-09T21:55:42","date_gmt":"2022-03-09T21:55:42","guid":{"rendered":"https:\/\/www.kindsonthegenius.com\/nodejs\/?p=268"},"modified":"2022-03-10T09:35:08","modified_gmt":"2022-03-10T09:35:08","slug":"node-js-rest-api-with-typescript-part-3-post-put-delete","status":"publish","type":"post","link":"https:\/\/kindsonthegenius.com\/nodejs\/node-js-rest-api-with-typescript-part-3-post-put-delete\/","title":{"rendered":"Node.js &#8211; REST API With TypeScript (Part 3 &#8211; POST\/PUT\/DELETE)"},"content":{"rendered":"<p>In this part, we would write the functions to POST, PUT and delete a country record from the database.<\/p>\n<ol>\n<li><a href=\"#t1\">Make a POST Request<\/a><\/li>\n<li><a href=\"#t2\">Make an UPDATE<\/a><\/li>\n<li><a href=\"#t3\">DELETE A Country<\/a><\/li>\n<\/ol>\n<p>&nbsp;<\/p>\n<h4><strong id=\"t1\">1. Make a POST Request<\/strong><\/h4>\n<p>Before you continue, you need to install a library that help parse the body of a http request. It is called body-parser. install it using <strong>npm install body parser.<\/strong><\/p>\n<p><strong>Add the BodyParser:<\/strong>\u00a0This is used to handle conversion to and from json.<br \/>\n<!-- HTML generated using hilite.me --><\/p>\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #008800; font-weight: bold;\">const<\/span> bodyParser <span style=\"color: #333333;\">=<\/span> require(<span style=\"background-color: #fff0f0;\">\"body-parser\"<\/span>);\r\napp.use(bodyParser.json());\r\n<\/pre>\n<p>&nbsp;<\/p>\n<p>The service method:<\/p>\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #008800; font-weight: bold;\">export<\/span> <span style=\"color: #008800; font-weight: bold;\">const<\/span> saveCountry <span style=\"color: #333333;\">=<\/span> async (country: <span style=\"color: #333399; font-weight: bold;\">any<\/span>) <span style=\"color: #333333;\">=&gt;<\/span> {\r\n    <span style=\"color: #008800; font-weight: bold;\">return<\/span> await db.one(<span style=\"background-color: #fff0f0;\">'INSERT INTO Country(capital, code, continent, description, nationality) '<\/span> <span style=\"color: #333333;\">+<\/span>\r\n        <span style=\"background-color: #fff0f0;\">'VALUES ($1, $2, $3, $4, $5)'<\/span>,\r\n        [country.capital, country.code, country.continent, country.description, country.nationality])\r\n}\r\n<\/pre>\n<p>&nbsp;<\/p>\n<p>The controller method:<\/p>\n<pre style=\"margin: 0; line-height: 125%;\">router.post(<span style=\"background-color: #fff0f0;\">'\/countries'<\/span>, (req: <span style=\"color: #333399; font-weight: bold;\">Request<\/span>, res: <span style=\"color: #333399; font-weight: bold;\">Response<\/span>) <span style=\"color: #333333;\">=&gt;<\/span> {\r\n    console.log(req.body);\r\n    countryService.saveCountry(req.body).then(\r\n        () <span style=\"color: #333333;\">=&gt;<\/span> {\r\n            res.status(<span style=\"color: #0000dd; font-weight: bold;\">200<\/span>).json({\r\n                message<span style=\"color: #333333;\">:<\/span> <span style=\"background-color: #fff0f0;\">\"Country was Inserted\"<\/span>\r\n            });\r\n        }\r\n    ).<span style=\"color: #008800; font-weight: bold;\">catch<\/span>((error)<span style=\"color: #333333;\">=&gt;<\/span>{\r\n            res.status(<span style=\"color: #0000dd; font-weight: bold;\">303<\/span>).json({\r\n                message<span style=\"color: #333333;\">:<\/span> <span style=\"background-color: #fff0f0;\">\"Error occured\"<\/span> <span style=\"color: #333333;\">+<\/span> error.message\r\n            })\r\n    });\r\n});\r\n<\/pre>\n<p>&nbsp;<\/p>\n<h4><strong id=\"t2\">2. Make an UPDATE (PUT Request)<\/strong><\/h4>\n<p>The update method in the country-service.ts file<\/p>\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #008800; font-weight: bold;\">export<\/span> <span style=\"color: #008800; font-weight: bold;\">const<\/span> updateCountry <span style=\"color: #333333;\">=<\/span> async (id:<span style=\"color: #333399; font-weight: bold;\">number<\/span>, country: <span style=\"color: #333399; font-weight: bold;\">any<\/span>) <span style=\"color: #333333;\">=&gt;<\/span> {\r\n    <span style=\"color: #008800; font-weight: bold;\">return<\/span> await db.one(<span style=\"background-color: #fff0f0;\">'UPDATE Country SET capital = $1, code = $2, continent = $3, description = $4, nationality = $5 '<\/span> <span style=\"color: #333333;\">+<\/span>\r\n        <span style=\"background-color: #fff0f0;\">'WHERE id = $6'<\/span>,\r\n        [country.capital, country.code, country.continent, country.description, country.nationality, id])\r\n}\r\n<\/pre>\n<p>&nbsp;<\/p>\n<p>The update method in the country-controller.ts file<\/p>\n<pre style=\"margin: 0; line-height: 125%;\">router.put(<span style=\"background-color: #fff0f0;\">'\/countries\/:id'<\/span>, (req: <span style=\"color: #333399; font-weight: bold;\">Request<\/span>, res: <span style=\"color: #333399; font-weight: bold;\">Response<\/span>) <span style=\"color: #333333;\">=&gt;<\/span> {\r\n    countryService.updateCountry(<span style=\"color: #007020;\">parseInt<\/span>(req.params.id), req.body).then(\r\n        () <span style=\"color: #333333;\">=&gt;<\/span> {\r\n            res.status(<span style=\"color: #0000dd; font-weight: bold;\">200<\/span>).json({\r\n                message<span style=\"color: #333333;\">:<\/span> <span style=\"background-color: #fff0f0;\">\"Country was successfully updated!\"<\/span>\r\n            });\r\n        }\r\n    ).<span style=\"color: #008800; font-weight: bold;\">catch<\/span>((error)<span style=\"color: #333333;\">=&gt;<\/span>{\r\n        res.status(<span style=\"color: #0000dd; font-weight: bold;\">303<\/span>).json({\r\n            message<span style=\"color: #333333;\">:<\/span> <span style=\"background-color: #fff0f0;\">\"Error occured\"<\/span> <span style=\"color: #333333;\">+<\/span> error.message\r\n        })\r\n    });\r\n});\r\n<\/pre>\n<p>&nbsp;<\/p>\n<h4><strong id=\"t3\">3. DELETE A Country<\/strong><\/h4>\n<p>The service method for delete<\/p>\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #008800; font-weight: bold;\">export<\/span> <span style=\"color: #008800; font-weight: bold;\">const<\/span> deleteCountry <span style=\"color: #333333;\">=<\/span> async (id:<span style=\"color: #333399; font-weight: bold;\">number<\/span>) <span style=\"color: #333333;\">=&gt;<\/span> {\r\n    <span style=\"color: #008800; font-weight: bold;\">return<\/span> await db.any(<span style=\"background-color: #fff0f0;\">'SELECT FROM Country WHERE id = $1'<\/span>, [id])\r\n}\r\n<\/pre>\n<p>&nbsp;<\/p>\n<p>The controller method<\/p>\n<pre style=\"margin: 0; line-height: 125%;\">router.<span style=\"color: #008800; font-weight: bold;\">delete<\/span>(<span style=\"background-color: #fff0f0;\">'\/countries\/:id'<\/span>, (req: <span style=\"color: #333399; font-weight: bold;\">Request<\/span>, res: <span style=\"color: #333399; font-weight: bold;\">Response<\/span>) <span style=\"color: #333333;\">=&gt;<\/span> {\r\n    countryService.deleteCountry(<span style=\"color: #007020;\">parseInt<\/span>(req.params.id)).then(\r\n        (country) <span style=\"color: #333333;\">=&gt;<\/span> {\r\n            res.send(country);\r\n        }).<span style=\"color: #008800; font-weight: bold;\">catch<\/span>((error) <span style=\"color: #333333;\">=&gt;<\/span> res.send(error.message))\r\n    ;\r\n});\r\n<\/pre>\n<p>&nbsp;<\/p>\n<p>At this point, you can run the application. Then use Postman to test the API endpoints.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this part, we would write the functions to POST, PUT and delete a country record from the database. Make a POST Request Make an &hellip; <\/p>\n","protected":false},"author":1,"featured_media":0,"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-268","post","type-post","status-publish","format-standard","hentry","category-node-js-tutorials","tag-api","tag-rest-api"],"_links":{"self":[{"href":"https:\/\/kindsonthegenius.com\/nodejs\/wp-json\/wp\/v2\/posts\/268","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=268"}],"version-history":[{"count":4,"href":"https:\/\/kindsonthegenius.com\/nodejs\/wp-json\/wp\/v2\/posts\/268\/revisions"}],"predecessor-version":[{"id":272,"href":"https:\/\/kindsonthegenius.com\/nodejs\/wp-json\/wp\/v2\/posts\/268\/revisions\/272"}],"wp:attachment":[{"href":"https:\/\/kindsonthegenius.com\/nodejs\/wp-json\/wp\/v2\/media?parent=268"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/kindsonthegenius.com\/nodejs\/wp-json\/wp\/v2\/categories?post=268"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/kindsonthegenius.com\/nodejs\/wp-json\/wp\/v2\/tags?post=268"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}