<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap" rel="stylesheet" /> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet" />

Python SDK

Installation

Install the SDK with pip (Python 3.9 or newer):

pip install countrydataapi

The only dependency is httpx.

Quick Start

from countrydataapi import CountryDataAPI

api = CountryDataAPI(api_key="your-api-key")

# Get all countries
countries = api.countries.get_all(lang="en")
print(countries["data"])

# Get country by ISO code
spain = api.countries.get_by_code("ES")
print(spain["data"][0]["country_name"])  # "Spain"

If api_key is omitted, the client reads the COUNTRYDATAAPI_API_KEY environment variable.

Configuration

api = CountryDataAPI(
    api_key="your-api-key",                     # Required (or env var)
    base_url="https://api.countrydataapi.com",  # Optional
    timeout=30.0,                               # Optional (seconds)
    max_retries=2,                              # Optional (0 disables retries)
    default_language="en",                      # Optional
)

Retries apply to timeouts, connection errors and 408/429/502/503/504 responses, with exponential backoff that honours Retry-After. Use the client as a context manager (with CountryDataAPI(...) as api:) or call api.close() to release the connection pool.

Countries

countries = api.countries.get_all(fields="id,country_name,country_flag_svg", lang="es", limit=50)
spain = api.countries.get_by_name("Spain")
country = api.countries.get_by_code("ES")
european = api.countries.get_by_region("Europe")
euro_countries = api.countries.get_by_currency("EUR")
spanish_speaking = api.countries.get_by_language("spa")
utc_countries = api.countries.get_by_timezone("UTC")
by_state = api.countries.get_by_state("California")
by_city = api.countries.get_by_city("Madrid")
by_zip = api.countries.get_by_zip_code("28001")

States

all_states = api.states.get_all()
spanish_states = api.states.get_by_country("Spain")
state = api.states.get_by_name("Madrid")
states = api.states.get_by_city("Madrid")
states_by_zip = api.states.get_by_zipcode("28001")

Cities

all_cities = api.cities.get_all(limit_token=100)
madrid = api.cities.get("Madrid")
spanish_cities = api.cities.get_by_country("Spain")
madrid_cities = api.cities.get_by_state("Madrid")

Zipcodes

zipcodes = api.zipcodes.get_by_country("Spain")
state_zipcodes = api.zipcodes.get_by_state("Madrid")
european_zipcodes = api.zipcodes.get_by_region("Europe")

Select (Country, State and City Dropdowns)

These endpoints cost only 1 token regardless of the number of results:

countries = api.select.countries(lang="en")["data"]
# [{"id": "...", "name": "Spain", "code": "ES", "phone_code": "+34", "flag": "..."}, ...]

states = api.select.states("ES")["data"]
# [{"id": "...", "name": "Comunidad de Madrid"}, ...]

cities = api.select.cities("Comunidad de Madrid", country="ES")["data"]
# [{"id": "...", "name": "Madrid"}, ...]

Places: Address Autocomplete

Create a session token when the address field gains focus and reuse it for every keystroke and for the final details() call. The whole session costs 1 token.

from countrydataapi import Places

session = Places.create_session()

res = api.places.autocomplete("mad", country="ES", types=["city"], session_token=session)
first = res["suggestions"][0]
print(first["description"])  # "Madrid, Comunidad de Madrid, Spain"

place = api.places.details(first["id"], type=first["type"], session_token=session)["place"]
print(place["postal"]["format"], place["country_info"]["currencies"])

Places: Validate a Postal Code

result = api.places.validate("ES", zipcode="28001")["result"]

if result["valid"]:
    print(result["normalized"]["state"]["name"])  # "Comunidad de Madrid"
else:
    for fix in result["corrections"]:
        print(f"{fix['component']}: did you mean {fix['suggestion']}?")

# Postcode format and regex, to validate client-side
fmt = api.places.postal_format(country="ES")["data"][0]["postal"]
print(fmt["regex"])  # "^\d{5}$"

Check Token Status

status = api.get_status()
print(f"Remaining tokens: {status['remainingTokens']}")

Request Options

Countries, states, cities and zipcodes methods accept:

Option Type Description
fields str Comma-separated list of fields to return
lang 'en' | 'es' | 'pt' | 'fr' | 'de' | 'it' Response language
limit int Maximum number of items to return
limit_token int Maximum tokens to use for this request

Any other keyword argument is sent as a query parameter.

Error Handling

from countrydataapi import (
    CountryDataAPIError,
    AuthenticationError,
    InsufficientTokensError,
    NotFoundError,
)

try:
    api.places.details("unknown-id", type="city")
except AuthenticationError:
    print("Invalid API key")
except InsufficientTokensError:
    print("No tokens remaining")
except NotFoundError as err:
    print(err.code, err.status_code)  # "NOT_FOUND" 404
except CountryDataAPIError as err:
    print("API error:", err.message)
Exception code HTTP
AuthenticationError INVALID_API_KEY 401
InsufficientTokensError INSUFFICIENT_TOKENS 402
ValidationError INVALID_PARAMETER 400
NotFoundError NOT_FOUND 404
RateLimitError RATE_LIMITED 429
ServerError INTERNAL_ERROR 5xx
APITimeoutError TIMEOUT -
APIConnectionError CONNECTION_ERROR -

Async Client

AsyncCountryDataAPI has the same methods, as coroutines:

import asyncio
from countrydataapi import AsyncCountryDataAPI

async def main() -> None:
    async with AsyncCountryDataAPI(api_key="your-api-key") as api:
        res = await api.places.autocomplete("lis", country="PT")
        print([s["description"] for s in res["suggestions"]])

asyncio.run(main())

Type Hints

Responses are plain dictionaries described by TypedDict classes, so your editor autocompletes the keys:

from countrydataapi.types import Country, CountryListResponse

response: CountryListResponse = api.countries.get_by_code("ES")
country: Country = response["data"][0]
print(country["country_name"])

Links

Compare plans and pricing: See CountryDataAPI pricing

Designed and developed by BePand