{"id":14682,"date":"2024-02-13T12:20:39","date_gmt":"2024-02-13T06:50:39","guid":{"rendered":"https:\/\/codexcoach.com\/?p=14682"},"modified":"2024-04-27T14:53:57","modified_gmt":"2024-04-27T09:23:57","slug":"how-to-create-get-request-api-with-node-js","status":"publish","type":"post","link":"https:\/\/codexcoach.com\/how-to-create-get-request-api-with-node-js\/","title":{"rendered":"5 Ways to Make HTTP Requests in Node.js (Creating REST API)"},"content":{"rendered":"\n<p>In Node.js, there are several ways to make HTTP requests. You can use the built-in HTTP and HTTPS modules that come with Node.js, the Fetch API that&#8217;s part of Node, or third-party packages like Axios, Got, SuperAgent, and node-fetch that you add to make things easier. can.<\/p>\n\n\n\n<p>In this guide, we&#8217;ll take a closer look at the built-in HTTPS module and the Fetch API. We&#8217;ll also examine some popular npm packages like Axios, Got, SuperAgent, and node-fetch, which help make HTTP requests easier.<\/p>\n\n\n\n<p>Let&#8217;s get into it!<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Prerequisites<\/h2>\n\n\n\n<ol>\n<li><strong>Node.js<\/strong>: You need to have Node.js version 14 or later installed on your computer, which could be set up directly or inside a Docker container.<\/li>\n\n\n\n<li><strong>npm Skills<\/strong>: Be familiar with basic npm commands like <code>npm init<\/code>, and know how to install new packages using <code>npm install &lt;module-name&gt;<\/code>.<\/li>\n\n\n\n<li><strong>Running JavaScript<\/strong>: Know how to run JavaScript files using the <code>node &lt;filename&gt;<\/code> command to check out what each script does.<\/li>\n\n\n\n<li><strong>JavaScript Knowledge<\/strong>: Understand JavaScript concepts like callbacks, promises, and async\/await for handling asynchronous operations.<\/li>\n<\/ol>\n\n\n\n<h2 class=\"wp-block-heading\">Example RESTful API<\/h2>\n\n\n\n<p>For our examples, we\u2019ll use the <a href=\"https:\/\/jsonplaceholder.typicode.com\/users\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">JSONPlaceholder API<\/a> to fetch and display data about 10 users, showing each user\u2019s username and ID on the console. You can find all the example code in a <a href=\"https:\/\/github.com\/geshan\/nodejs-requests\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">GitHub repository<\/a> linked in this guide.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Methods for Making HTTP Requests in Node.js<\/h2>\n\n\n\n<p>We&#8217;ll explore five different ways to send GET requests to the JSONPlaceholder API, starting with the built-in HTTP(S) module in Node.js as our first example.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">5 Ways to Make HTTP Requests in Node.js<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"http--the-standard-library\">Standard Node.js HTTP(S) Module<\/h3>\n\n\n\n<p>The default HTTP module in the standard library is first on our hit parade. You don&#8217;t need to install any external dependencies with this module. However, it is not very user-friendly compared to other solutions.<\/p>\n\n\n\n<p>In the following code, a GET request will be sent to NASA&#8217;s API and the URL for that day&#8217;s astronomy picture and explanation will be printed: JavaScript<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-plain\"><code>const https = require(&#39;https&#39;);\n\nhttps.get(&#39;https:\/\/api.nasa.gov\/planetary\/apod?api_key=DEMO_KEY&#39;, (resp) =&gt; {\n  let data = &#39;&#39;;\n\n  \/\/ A chunk of data has been received.\n  resp.on(&#39;data&#39;, (chunk) =&gt; {\n    data += chunk;\n  });\n\n  \/\/ The whole response has been received. Print out the result.\n  resp.on(&#39;end&#39;, () =&gt; {\n    console.log(JSON.parse(data).explanation);\n  });\n\n}).on(&quot;error&quot;, (err) =&gt; {\n  console.log(&quot;Error: &quot; + err.message);\n});<\/code><\/pre><\/div>\n\n\n\n<p>The majority of HTTP and HTTPS modules have fairly low-level functionality. To receive the response data in chunks, you should not provide a callback function to execute after all the data is received. Additionally, you must manually parse the response data. In a JSON format, this is fairly trivial, but it still requires additional steps.<\/p>\n\n\n\n<p>We&#8217;ll also need the HTTP module if the API we&#8217;re using communicates over HTTPS since this module doesn&#8217;t support HTTPS by default.<\/p>\n\n\n\n<p>Although it might take a little more work, it&#8217;s a great utility for those who don&#8217;t want to add a lot of dependencies or access low-level features to their codebase.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"node-fetch\">Node-Fetch<\/h3>\n\n\n\n<p>In Node.js, node-fetch translates the browser library <code><strong>window.fetch<\/strong><\/code> as a lightweight module. Unlike HTTP, you must install this from npm as a dependency.<\/p>\n\n\n\n<p>Run the following commands from the directory you want your code to reside in: JavaScript<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-plain\"><code>npm install node-fetch@2.6.0<\/code><\/pre><\/div>\n\n\n\n<p>As this library uses promises, we can use async\/await syntax with it as well: JavaScript<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-plain\"><code>const fetch = require(&#39;node-fetch&#39;);\n\n(async () =&gt; {\n  try {\n\n    const response = await fetch(&#39;https:\/\/api.nasa.gov\/planetary\/apod?api_key=DEMO_KEY&#39;)\n    const json = await response.json()\n\n    console.log(json.url);\n    console.log(json.explanation);\n  } catch (error) {\n    console.log(error.response.body);\n  }\n})();<\/code><\/pre><\/div>\n\n\n\n<p>In this library, the response is converted to JSON via a built-in function, but it doesn&#8217;t do it automatically as it does in some of the libraries below. For browser users who are familiar with the Fetch API, this is great.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"axios\">Axios<\/h3>\n\n\n\n<p>Node.js and the browser both support <a href=\"https:\/\/github.com\/axios\/axios\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">Axios<\/a>, a <a href=\"https:\/\/www.promisejs.org\/\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">Promise<\/a>-based HTTP client. Promises are very useful when dealing with code that requires a complex chain of events. There are several solutions to the problem of writing asynchronous code, and Promises are one of them. Swift and other languages can also benefit from them.<\/p>\n\n\n\n<p>You can install Axios from npm by entering the following command: JavaScript<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-plain\"><code>npm install axios@0.21.1<\/code><\/pre><\/div>\n\n\n\n<p>The code below notes the URL and explains the day&#8217;s astronomical image.JavaScript<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-plain\"><code>const axios = require(&#39;axios&#39;);\n\naxios.get(&#39;https:\/\/api.nasa.gov\/planetary\/apod?api_key=DEMO_KEY&#39;)\n  .then(response =&gt; {\n    console.log(response.data.url);\n    console.log(response.data.explanation);\n  })\n  .catch(error =&gt; {\n    console.log(error);\n  });<\/code><\/pre><\/div>\n\n\n\n<p>Axios also parses JSON answers by default. That&#8217;s completely convenient! You can see that error handling is completed. We now use promises, thus <code><strong>.catch()<\/strong><\/code> is necessary.<\/p>\n\n\n\n<p>Axios supports many concurrent queries. For example, if you wish to capture an astronomical image of two days simultaneously:JavaScript<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-plain\"><code>var axios = require(&#39;axios&#39;);\n\naxios.all([\n  axios.get(&#39;https:\/\/api.nasa.gov\/planetary\/apod?api_key=DEMO_KEY&date=2017-08-03&#39;),\n  axios.get(&#39;https:\/\/api.nasa.gov\/planetary\/apod?api_key=DEMO_KEY&date=2017-08-02&#39;)\n]).then(axios.spread((response1, response2) =&gt; {\n  console.log(response1.data.url);\n  console.log(response2.data.url);\n})).catch(error =&gt; {\n  console.log(error);\n});<\/code><\/pre><\/div>\n\n\n\n<p>Asynchronous code may quickly become overly difficult and unpleasant to work with, and the way Axios approaches this issue may make your life simpler in the long term.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"superagent\">SuperAgent<\/h3>\n\n\n\n<p><a href=\"https:\/\/github.com\/ladjs\/superagent\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">SuperAgent<\/a>, like Axios, is a popular package for making AJAX queries in the browser but also supports Node.js. Install SuperAgent using the following command:JavaScript<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-plain\"><code>npm install superagent@6.1.0<\/code><\/pre><\/div>\n\n\n\n<p>SuperAgent has additional methods, such as <code><strong>query()<\/strong><\/code>, for adding arguments to requests. In earlier instances, we manually added them to the URL, but observe how SuperAgent provides a method to do so:JavaScript<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-plain\"><code>const superagent = require(&#39;superagent&#39;);\n\nsuperagent.get(&#39;https:\/\/api.nasa.gov\/planetary\/apod&#39;)\n.query({ api_key: &#39;DEMO_KEY&#39;, date: &#39;2017-08-02&#39; })\n.end((err, res) =&gt; {\n  if (err) { return console.log(err); }\n  console.log(res.body.url);\n  console.log(res.body.explanation);\n});<\/code><\/pre><\/div>\n\n\n\n<p>You don&#8217;t have to parse the JSON answer manually, which is a nice feature.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"got\">Got<\/h3>\n\n\n\n<p><a href=\"https:\/\/github.com\/sindresorhus\/got\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">Got<\/a> is another option for a lightweight library. It may also be used in <strong>Codexcoach<\/strong> Functions.<\/p>\n\n\n\n<p>Again, install Got with npm:JavaScript<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-plain\"><code>npm install got@7.1.0<\/code><\/pre><\/div>\n\n\n\n<p>Got, like Axios, operates with promises. The following code will work as the other examples do:JavaScript<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-plain\"><code>const got = require(&#39;got&#39;);\n\ngot(&#39;https:\/\/api.nasa.gov\/planetary\/apod?api_key=DEMO_KEY&#39;, { json: true }).then(response =&gt; {\n  console.log(response.body.url);\n  console.log(response.body.explanation);\n}).catch(error =&gt; {\n  console.log(error.response.body);\n});<\/code><\/pre><\/div>\n\n\n\n<p>Got is ideal if you want a smaller library that is less &#8220;bloated&#8221; than something like Request.<\/p>\n<div id=\"ezoic-pub-ad-placeholder-118\"><\/div>","protected":false},"excerpt":{"rendered":"<p>In Node.js, there are several ways to make HTTP requests. You can use the built-in HTTP and HTTPS modules that come with Node.js, the Fetch API that&#8217;s part of Node, or third-party packages like Axios, Got, SuperAgent, and node-fetch that you add to make things easier. can. In this guide, we&#8217;ll take a closer look [&#8230;]<\/p>\n","protected":false},"author":6,"featured_media":15467,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_aib_schema_json_ld":""},"categories":[225],"tags":[],"_links":{"self":[{"href":"https:\/\/codexcoach.com\/wp-json\/wp\/v2\/posts\/14682"}],"collection":[{"href":"https:\/\/codexcoach.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codexcoach.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codexcoach.com\/wp-json\/wp\/v2\/users\/6"}],"replies":[{"embeddable":true,"href":"https:\/\/codexcoach.com\/wp-json\/wp\/v2\/comments?post=14682"}],"version-history":[{"count":7,"href":"https:\/\/codexcoach.com\/wp-json\/wp\/v2\/posts\/14682\/revisions"}],"predecessor-version":[{"id":15466,"href":"https:\/\/codexcoach.com\/wp-json\/wp\/v2\/posts\/14682\/revisions\/15466"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codexcoach.com\/wp-json\/wp\/v2\/media\/15467"}],"wp:attachment":[{"href":"https:\/\/codexcoach.com\/wp-json\/wp\/v2\/media?parent=14682"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codexcoach.com\/wp-json\/wp\/v2\/categories?post=14682"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codexcoach.com\/wp-json\/wp\/v2\/tags?post=14682"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}