Welcome to country-state-city microservice

JavaScript Usage Examples

Here are some JavaScript examples using the Fetch API to interact with the four endpoints.

1. Get Countries

Endpoint

GET https://api.country-state-city.rebuscando.info/public/getCountries

Example

fetch('https://api.country-state-city.rebuscando.info/public/getCountries')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok ' + response.statusText);
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('There was a problem with the fetch operation:', error));

2. Get States

Endpoint

GET https://api.country-state-city.rebuscando.info/public/getStates?idcountry={idcountry}

Example

const idcountry = 207; // Example country ID
const url = `https://api.country-state-city.rebuscando.info/public/getStates?idcountry=${idcountry}`;
fetch(url)
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok ' + response.statusText);
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('There was a problem with the fetch operation:', error));

3. Get Cities

Endpoint

GET https://api.country-state-city.rebuscando.info/public/getCities?idstate={idstate}

Example

const idstate = 5109; // Example state ID
const url = `https://api.country-state-city.rebuscando.info/public/getCities?idstate=${idstate}`;
fetch(url)
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok ' + response.statusText);
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('There was a problem with the fetch operation:', error));

4. Get State and Cities by Postal Code and Country ID

Endpoint

GET https://api.country-state-city.rebuscando.info/public/getStateAndCitiesByPostalCodeAndCountryId?idcountry={idcountry}&postalcode={postalcode}

Example

const postalcode = '29001'; // Example postal code
const idcountry = 207; // Example country ID
const url = `https://api.country-state-city.rebuscando.info/public/getStateAndCitiesByPostalCodeAndCountryId?idcountry=${idcountry}&postalcode=${postalcode}`fetch(url).then(response => {
  if (!response.ok) {
    throw new Error('Network response was not ok ' + response.statusText);
}
  return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('There was a problem with the fetch operation:', error)); 

 

These examples demonstrate how to make GET requests to each of the endpoints, handle the response, and manage errors. You can test these examples in a browser’s console or integrate them into your JavaScript application.