Authentication overview

CountryStateCity provides programmatic access to its hierarchical geospatial dataset, including countries, their states, and respective cities. Access to the API is secured using a single API key, a common method for controlling access to web services. This key serves as both an identifier for the client making the request and a token for authorization, ensuring that only authenticated applications can retrieve location data CountryStateCity API documentation.

The API key model simplifies the authentication process for developers by requiring a single credential. This approach is suitable for applications that primarily retrieve public or semi-public data where user-specific authorization is not required. For CountryStateCity, the API key enables usage tracking, rate limit enforcement, and distinguishes between free and paid tier access.

When integrating the CountryStateCity API, developers include their unique API key directly in each request. The API then validates this key against its records before processing the request and returning the requested country, state, or city data. This mechanism ensures that only legitimate and authorized applications consume API resources, contributing to the stability and security of the service.

Supported authentication methods

CountryStateCity exclusively supports API Key authentication for accessing its services. This method is widely adopted for public and internal APIs due to its simplicity and ease of implementation compared to more complex schemes like OAuth 2.0 or mutual TLS.

The API key functions as a unique identifier and a secret token. When an application sends a request to the CountryStateCity API, it must include this key. The API backend then verifies the key's validity and permissions before responding. This allows CountryStateCity to manage access, enforce rate limits, and provide usage analytics for each key holder CountryStateCity API guide.

While API keys offer a straightforward authentication mechanism, their security relies heavily on how they are stored and transmitted. Best practices dictate that API keys should be treated as sensitive credentials, similar to passwords, and protected from unauthorized exposure. For client-side applications, proxy servers are often recommended to prevent direct exposure of the key in frontend code.

The following table summarizes the authentication method supported by CountryStateCity:

Method When to Use Security Level
API Key Accessing public or semi-public data, server-to-server communication, client applications using a proxy. Moderate (depends heavily on secure storage and transmission practices).

Getting your credentials

To obtain an API key for CountryStateCity, you need to register for an account on their official website. The process typically involves a few steps:

  1. Sign Up: Navigate to the CountryStateCity homepage and register for a new account. This usually requires an email address and password.
  2. Account Activation: Verify your email address by clicking the link sent to your inbox. This step ensures the legitimacy of your account.
  3. Dashboard Access: Log in to your newly created account. You will typically be directed to a developer dashboard or a similar portal.
  4. Generate API Key: Within the dashboard, look for a section related to 'API Keys,' 'Credentials,' or 'Settings.' There should be an option to generate a new API key. CountryStateCity provides a single key for all API interactions.
  5. Store Your Key: Once generated, copy your API key and store it securely. It is crucial to treat this key as a sensitive credential. CountryStateCity's documentation emphasizes that API keys should not be hardcoded directly into client-side applications or publicly exposed CountryStateCity developer portal.

For the free tier, which offers up to 100 requests per day, an API key is automatically assigned upon registration. If your usage exceeds this limit or you require higher performance and additional features, you can upgrade to a paid plan. Paid plans, such as the Basic tier starting at $5/month for 2,500 requests/day, use the same API key mechanism but unlock higher rate limits CountryStateCity pricing details.

It is recommended to regenerate your API key periodically or if you suspect it has been compromised. Most developer dashboards provide an option to revoke old keys and generate new ones, minimizing the risk of unauthorized access.

Authenticated request example

Once you have your CountryStateCity API key, you can include it in your API requests. The key is typically passed as a header or a query parameter, depending on the API's design. CountryStateCity expects the API key to be sent as a custom header named X-CSCAPIKEY.

Here's an example of how to make an authenticated request using cURL, a common command-line tool for making HTTP requests:

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

In this example:

  • -X GET specifies the HTTP method (GET, for retrieving data).
  • 'https://api.countrystatecity.in/v1/countries' is the API endpoint for fetching a list of all countries.
  • -H 'X-CSCAPIKEY: YOUR_API_KEY' is the crucial part for authentication. Replace YOUR_API_KEY with the actual API key you obtained from your CountryStateCity dashboard.
  • -H 'Content-Type: application/json' informs the server that the expected response format is JSON.

CountryStateCity also provides SDKs for various programming languages, such as JavaScript, which simplify the process of making authenticated requests. For example, a JavaScript implementation might look like this:

async function fetchCountries() {
  const apiKey = 'YOUR_API_KEY'; // In a real application, fetch securely
  const response = await fetch('https://api.countrystatecity.in/v1/countries', {
    method: 'GET',
    headers: {
      'X-CSCAPIKEY': apiKey,
      'Content-Type': 'application/json'
    }
  });

  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
  }
  const data = await response.json();
  console.log(data);
}

fetchCountries().catch(error => console.error('Error fetching countries:', error));

It's important to note that directly embedding API keys in client-side JavaScript (as shown for illustrative purposes) is generally not recommended for production applications due to security risks. For production, consider server-side proxying or environment variables.

Security best practices

Protecting your CountryStateCity API key is crucial to prevent unauthorized access, potential abuse of your account, and exceeding your rate limits. Adhering to security best practices for API keys is essential for maintaining the integrity and availability of your application.

1. Do not expose API keys in client-side code

Never embed your API key directly in client-side code (e.g., JavaScript in a web browser, mobile app binaries). If exposed, malicious actors could extract the key and use it to make unauthorized requests on your behalf. This is a common vulnerability that can lead to unexpected charges or service interruptions.

2. Use environment variables or secret management services

For server-side applications, store your API key in environment variables rather than hardcoding it into your source code. This approach keeps the key out of version control systems and allows for easier rotation. For more complex deployments, consider using secret management services like AWS Secrets Manager AWS Secrets Manager overview or Google Cloud Secret Manager Google Cloud Secret Manager guide, which provide centralized, secure storage and access control for sensitive credentials.

3. Implement server-side proxying for client applications

If your application requires client-side access to the CountryStateCity API, implement a server-side proxy. The client application makes requests to your server, which then forwards the request to the CountryStateCity API, adding the API key on the server side. The server then returns the API response to the client. This ensures the API key is never exposed to the public internet via the client.

4. Restrict API key usage (if supported)

While CountryStateCity's API key is a general access token, if an API provider offers features to restrict API keys by IP address or HTTP referrer, always utilize them. This adds an extra layer of security, ensuring that even if a key is compromised, it can only be used from authorized locations or domains. CountryStateCity currently does not offer granular IP or referrer restrictions for its API keys.

5. Monitor API usage and implement rate limits

Regularly monitor your API usage patterns. Unexpected spikes in requests could indicate unauthorized use of your API key. While CountryStateCity enforces its own rate limits, consider implementing client-side rate limiting in your application to prevent accidental overuse and to detect potential misuse early.

6. Rotate API keys periodically

Establish a routine for rotating your API keys. Regularly generating new keys and revoking old ones reduces the window of opportunity for a compromised key to be exploited. This practice is especially important after personnel changes or if there is any suspicion of a security breach.

7. Securely transmit data via HTTPS

Always ensure that all communication with the CountryStateCity API occurs over HTTPS. HTTPS encrypts data in transit, protecting your API key and other sensitive information from interception by eavesdroppers. The CountryStateCity API endpoints are configured to require HTTPS.