Accessing Indian Cities API using JavaScript

If you're looking for an API that provides data on Indian cities, look no further than the Indian Cities API (https://indian-cities-api-nocbegfhqg.now.sh/). This API provides information on over 400 Indian cities, including their names, states, and populations.

In order to access the API using JavaScript, you'll need to make HTTP requests using either XMLHttpRequest or fetch().

Making an HTTP GET request

To request data from the API, we'll use the HTTP GET method. Here's an example of how to make a basic GET request using fetch():

fetch('https://indian-cities-api-nocbegfhqg.now.sh/cities')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.log(error));

This code makes a GET request to the /cities endpoint of the API and logs the response data to the console. The response.json() method returns a promise that resolves with the parsed JSON response data.

Filtering results

The API supports filtering results by state. To do this, we can add a state parameter to our request URL. Here's an example that fetches all the cities in the state of Maharashtra:

const state = 'Maharashtra';
fetch(`https://indian-cities-api-nocbegfhqg.now.sh/cities?state=${state}`)
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.log(error));

Sorting results

The API supports sorting the results by name or population. To do this, we can add a sort parameter to our request URL. Here's an example that fetches all the cities in the state of Karnataka, sorted by population in descending order:

const state = 'Karnataka';
const sortBy = 'population_desc';
fetch(`https://indian-cities-api-nocbegfhqg.now.sh/cities?state=${state}&sort=${sortBy}`)
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.log(error));

Conclusion

Using the Indian Cities API is a great way to fetch data on Indian cities for your web or mobile app. By making HTTP requests with JavaScript, you can easily retrieve the data you need and display it to your users. Happy coding!

Related APIs in Geocoding