Nikhil
Nikhil

Reputation: 2318

Nodejs equivalent of sending one GET request to the server to fetch data from the API

This is the API endpoint where I am trying to get the data from https://geocode.xyz/?locate=Warsaw,Poland&json=1.

When I run this in the browser or in the Postman, I get a successful response. This is expected output snippet.

{ "standard" : { "addresst" : {}, "city" : "Warsaw",
"prov" : "PL", "countryname" : "Poland", "postal" : {},
"confidence" : "0.7" }, "longt" : "21.03539", "alt" : {
"loc" : { "longt" : "21.23400", "prov" : "PL",
"city" : "Warsaw", "countryname" : "Poland", "postal" : "05-077", "region" : {}, "latt" : "52.21890" } }, "elevation" : {}, "latt" : "52.23275"}

I am trying to get the same output using nodejs. I tried the default https and request module but of no avail. This is what I have:

const request = require('request');

request('https://geocode.xyz/?locate=Warsaw,Poland&json=1', { json: true }, (err, res, body) => {
  if (err) { return console.log(err); }
    console.log(body);
});

This is the output I am seeing:

{ success: false, error: { code: '006', message: 'Request Throttled.' } }

The API for the free version expects just 1 request per second.

Throttled API access is free. Rate limit: up to 1 API call per sec. API (Throttled to no more that 1 request per second for all free port users combined. eg., if 2 free requests come at the same time, each gets throttled to 2 seconds per request).

How do I limit my code to send just one request? How am I able to get a response while using browser/postman. How do I achieve the same expected, successful response using nodejs?

This is also what I tried using https and I got the same response:

const https = require('https');

https.get('https://geocode.xyz/?locate=Warsaw,Poland&json=1', (resp) => {
  let data = '';

  // A chunk of data has been recieved.
  resp.on('data', (chunk) => {
    data += chunk;
  });

  // The whole response has been received. Print out the result.
  resp.on('end', () => {
    console.log(JSON.parse(data));
  });

}).on("error", (err) => {
  console.log("Error: " + err.message);
});

Upvotes: 0

Views: 147

Answers (1)

Dash
Dash

Reputation: 812

From the Geocode.xyz doc

(...) no more than 1 request per second for all un-authenticated users combined

You have to create an account, get an API key and use it. Your issue should be solved.

You have 10 requests/s free plan.

Upvotes: 1

Related Questions