Getting started overview

Integrating the CountryStateCity API involves a sequence of steps designed to get developers making authenticated requests quickly. This guide focuses on initial setup: account creation, API key retrieval, and executing a basic API call to fetch location data. The API is structured to provide hierarchical country, state, and city information, useful for applications requiring location input fields or geographical data lookups.

The CountryStateCity API facilitates the retrieval of geographical data, specifically countries, their states, and the cities within those states (CountryStateCity API documentation). It is often utilized in web forms for address autofill, e-commerce platforms for shipping calculations, or user registration processes requiring location-specific data. While the API provides structured location data, it does not perform full address geocoding or reverse geocoding, which typically involves converting street addresses into geographical coordinates or vice versa (Google Maps Geocoding API overview).

Quick Reference: Getting Started Steps

The following table summarizes the essential steps to get started with CountryStateCity:

Step What to Do Where
1. Sign Up Create a new account. CountryStateCity homepage
2. Get API Key Locate your unique API key in the developer dashboard. CountryStateCity developer dashboard
3. Understand Endpoints Review the available API endpoints for countries, states, and cities. CountryStateCity API reference
4. Make First Request Use cURL or a preferred programming language (JavaScript, Python, PHP) to call an endpoint with your API key. Code editor/terminal
5. Handle Response Parse the JSON response to extract location data. Code editor

Create an account and get keys

Before making any API calls, you need to register for a CountryStateCity account and obtain an API key. This key acts as your credential for authenticating requests and accessing the service's data. Without a valid API key, all requests will be rejected by the API.

Account Creation Process

  1. Visit the CountryStateCity Website: Navigate to the CountryStateCity homepage.
  2. Sign Up: Look for a "Sign Up" or "Get API Key" button, typically located in the navigation bar or prominent on the landing page.
  3. Provide Details: Complete the registration form, which usually requires an email address, username, and password. You may also need to agree to terms of service and privacy policies.
  4. Email Verification: After submitting your details, check your email inbox for a verification link. Clicking this link confirms your account and often grants immediate access to the developer dashboard.

Retrieving Your API Key

Once your account is active, your API key will be accessible through your developer dashboard:

  1. Log In: Go to the CountryStateCity website and log into your newly created account.
  2. Access Dashboard: You will typically be redirected to your personal dashboard or a "My Account" section.
  3. Locate API Key: Within the dashboard, there should be a clearly labeled section for "API Keys," "Credentials," or "Developer Settings." Your unique API key will be displayed here. It is a long alphanumeric string.
  4. Copy and Secure: Copy your API key and store it securely. Treat your API key like a password; do not hardcode it directly into client-side code that could be publicly exposed, and avoid sharing it unnecessarily. For server-side applications, consider using environment variables to manage API keys (Azure functions app settings for environment variables).

The free tier allows up to 100 requests per day, suitable for initial development and testing (CountryStateCity pricing details). If your application requires higher request volumes, you will need to upgrade to a paid plan.

Your first request

With your API key in hand, you can now make your first authenticated request to the CountryStateCity API. This example demonstrates fetching a list of all countries using a simple cURL command, which is a common method for testing RESTful APIs from the command line.

API Endpoint Structure

CountryStateCity API endpoints follow a RESTful convention. For instance, to get a list of countries, you might use an endpoint like /api/v1/countries. The API key is typically passed as a header or a query parameter, as specified in the CountryStateCity API documentation.

Example: Fetching All Countries with cURL

Replace YOUR_API_KEY with the actual API key you obtained from your dashboard.

curl -X GET \
  'https://api.countrystatecity.in/v1/countries' \
  -H 'X-CSCAPI-KEY: YOUR_API_KEY' \
  -H 'Content-Type: application/json'

Explanation:

  • curl -X GET: Specifies an HTTP GET request.
  • 'https://api.countrystatecity.in/v1/countries': This is the target endpoint for retrieving country data.
  • -H 'X-CSCAPI-KEY: YOUR_API_KEY': This header passes your unique API key for authentication. The header name X-CSCAPI-KEY is specific to CountryStateCity and should be used as documented.
  • -H 'Content-Type: application/json': Indicates that the client expects a JSON response.

Expected Response

A successful request will return a JSON array containing objects representing countries. Each country object will include properties such as its name, ISO codes, and potentially other relevant data. An example partial response structure might look like this:

[
  {
    "id": 1,
    "name": "Afghanistan",
    "iso2": "AF",
    "iso3": "AFG",
    "numeric_code": "004",
    "phone_code": "93",
    "capital": "Kabul",
    "currency": "AFN",
    "currency_name": "Afghan afghani",
    "currency_symbol": "؋",
    "tld": ".af",
    "native": "افغانستان",
    "region": "Asia",
    "subregion": "Southern Asia",
    "timezones": [
      {
        "zoneName": "Asia/Kabul",
        "gmtOffset": 16200,
        "gmtOffsetName": "UTC+04:30",
        "abbreviation": "AFT",
        "tzName": "Afghanistan Time"
      }
    ],
    "latitude": "33.00000000",
    "longitude": "65.00000000",
    "emoji": "🇦🇫",
    "emojiU": "U+1F1E6 U+1F1EB"
  },
  {
    "id": 2,
    "name": "Åland Islands",
    "iso2": "AX",
    "iso3": "ALA",
    "numeric_code": "248",
    "phone_code": "+358-18",
    "capital": "Mariehamn",
    "currency": "EUR",
    "currency_name": "Euro",
    "currency_symbol": "€",
    "tld": ".ax",
    "native": "Åland",
    "region": "Europe",
    "subregion": "Northern Europe",
    "timezones": [
      {
        "zoneName": "Europe/Mariehamn",
        "gmtOffset": 7200,
        "gmtOffsetName": "UTC+02:00",
        "abbreviation": "EET",
        "tzName": "Eastern European Time"
      }
    ],
    "latitude": "60.11666700",
    "longitude": "19.90000000",
    "emoji": "🇦🇽",
    "emojiU": "U+1F1E6 U+1F1ED"
  }
]

This response confirms that your API key is valid and your request was successfully processed. You can then parse this JSON data in your application to display or utilize the country information.

Common next steps

After successfully making your first API call, you can proceed with further integration and leverage the full capabilities of the CountryStateCity API. Common next steps include:

Fetching States and Cities

Once you have a list of countries, you can use their ISO codes (e.g., iso2 or iso3) to query for states within a specific country, and then cities within a specific state. The CountryStateCity API provides specific endpoints for these hierarchical queries.

# Get states in a specific country (e.g., United States - US)
curl -X GET \
  'https://api.countrystatecity.in/v1/countries/US/states' \
  -H 'X-CSCAPI-KEY: YOUR_API_KEY'

# Get cities in a specific state (e.g., California - CA, within US)
curl -X GET \
  'https://api.countrystatecity.in/v1/countries/US/states/CA/cities' \
  -H 'X-CSCAPI-KEY: YOUR_API_KEY'

Always refer to the CountryStateCity API documentation for the precise endpoint paths and required parameters for these nested requests.

Integrating with Client-Side Libraries (JavaScript SDK)

If you are developing a web application, you might use the provided JavaScript SDK or integrate the API using a client-side HTTP library like fetch or axios. The JavaScript SDK can simplify the process of making requests and handling responses directly in your frontend code, especially for dynamic forms.

// Example using fetch in JavaScript (for client-side)
const API_KEY = 'YOUR_API_KEY';

async function getCountries() {
  try {
    const response = await fetch('https://api.countrystatecity.in/v1/countries', {
      method: 'GET',
      headers: {
        'X-CSCAPI-KEY': API_KEY,
        'Content-Type': 'application/json'
      }
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const data = await response.json();
    console.log(data);
    return data;
  } catch (error) {
    console.error('Error fetching countries:', error);
  }
}

getCountries();

Error Handling and Rate Limiting

Implement robust error handling in your application to gracefully manage scenarios such as invalid API keys, rate limit exceeded errors, or network issues. The CountryStateCity API will return specific HTTP status codes and error messages to indicate problems.

  • 401 Unauthorized: Typically indicates an invalid or missing API key.
  • 429 Too Many Requests: Occurs when you exceed your plan's request limit.
  • 404 Not Found: The requested resource (e.g., a country or state) does not exist or the endpoint path is incorrect.

Monitor your API usage against your plan's limits, especially if you are on the CountryStateCity free tier, which has a limit of 100 requests per day.

Troubleshooting the first call

Encountering issues during your first API call is common. Here are some troubleshooting steps for typical problems when interacting with the CountryStateCity API:

1. Invalid API Key (401 Unauthorized)

  • Check for Typos: Ensure your X-CSCAPI-KEY header value exactly matches the key from your dashboard. API keys are case-sensitive.
  • Correct Header Name: Verify that the header name is precisely X-CSCAPI-KEY as specified in the CountryStateCity API documentation.
  • Key Status: Log into your CountryStateCity dashboard to confirm your API key is active and not revoked or expired.

2. Rate Limit Exceeded (429 Too Many Requests)

  • Usage Check: Review your API usage in your CountryStateCity dashboard. The free tier has a limit of 100 requests per day.
  • Wait and Retry: If you've hit the limit, wait for the rate limit window to reset or upgrade to a higher CountryStateCity pricing plan if persistent higher usage is required.
  • Caching: Implement client-side or server-side caching for frequently accessed data to reduce the number of API calls (Cloudflare CDN cache basics).

3. Endpoint Not Found (404 Not Found)

  • Verify URL: Double-check the API endpoint URL for any typos or incorrect path segments. Compare it directly with the CountryStateCity API reference.
  • HTTP Method: Ensure you are using the correct HTTP method (e.g., GET for retrieval).
  • Resource Existence: Confirm that the country, state, or city you are trying to query actually exists in the database and that its ID or code is correct.

4. Network Issues

  • Internet Connection: Verify that your machine has a stable internet connection.
  • Firewall/Proxy: If you are in a corporate environment, check if a firewall or proxy is blocking outgoing requests to the API endpoint.

5. Malformed Request or Invalid JSON

  • Headers: Ensure all required headers (like Content-Type: application/json) are correctly set.
  • JSON Structure: If you are sending data (though less common for initial GET requests), ensure your JSON payload is valid.

By systematically checking these points, you can often identify and resolve issues preventing a successful first API call.