Welcome to country-state-city microservice

Python Usage Examples

Here are some Python examples using the requests library to interact with the four endpoints.

1. Get Countries

Endpoint

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

Example

import requests

url = 'https://api.country-state-city.rebuscando.info/public/getCountries'

try:
response = requests.get(url)
response.raise_for_status() # Check if the request was successful
countries = response.json()
print(countries)
except requests.exceptions.HTTPError as http_err:
print(f'HTTP error occurred: {http_err}')
except Exception as err:
print(f'Other error occurred: {err}')

2. Get States

Endpoint

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

Example

import requests

idcountry = 207 # Example country ID
url = f'https://api.country-state-city.rebuscando.info/public/getStates?idcountry={idcountry}'

try:
response = requests.get(url)
response.raise_for_status() # Check if the request was successful
states = response.json()
print(states)
except requests.exceptions.HTTPError as http_err:
print(f'HTTP error occurred: {http_err}')
except Exception as err:
print(f'Other error occurred: {err}')

3. Get Cities

Endpoint

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

Example

import requests

idstate = 5109 # Example state ID
url = f'https://api.country-state-city.rebuscando.info/public/getCities?idstate={idstate}'

try:
response = requests.get(url)
response.raise_for_status() # Check if the request was successful
cities = response.json()
print(cities)
except requests.exceptions.HTTPError as http_err:
print(f'HTTP error occurred: {http_err}')
except Exception as err:
print(f'Other error occurred: {err}')

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

import requests

postalcode = '29001' # Example postal code
idcountry = 207 # Example country ID
url = f'https://api.country-state-city.rebuscando.info/public/getStateAndCitiesByPostalCodeAndCountryId?idcountry={idcountry}&postalcode={postalcode}'

try:
response = requests.get(url)
response.raise_for_status() # Check if the request was successful
state_and_cities = response.json()
print(state_and_cities)
except requests.exceptions.HTTPError as http_err:
print(f'HTTP error occurred: {http_err}')
except Exception as err:
print(f'Other error occurred: {err}')

 

These examples demonstrate how to make GET requests to each of the endpoints, handle the response, and manage errors using Python and the requests library.

To run these examples, you need to install the requests library, which can be done using pip:

pip install requests

 

You can then run the examples in your Python environment.