curl -X GET 'https://api.countrystatecity.in/v1/countries' \
  -H 'X-CSCAPI-KEY: invalid_key'
{
  "error": "Unauthorized. You shouldn't be here."
}

API Key Authentication

The Country State City API uses API key authentication for all endpoints. Your API key must be included in every request using the X-CSCAPI-KEY header.
1

Get Your API Key

Register at our portal to obtain your API key.
API keys are generated instantly and are ready to use immediately.
2

Add to Request Headers

Include your API key in the X-CSCAPI-KEY header for every request:
curl -X GET 'https://api.countrystatecity.in/v1/countries' \
  -H 'X-CSCAPI-KEY: YOUR_API_KEY'
3

Handle Responses

Check for authentication errors and implement proper error handling:
if (response.status === 401) {
  console.error('Invalid API key');
} else if (response.ok) {
  const data = await response.json();
  console.log('Success:', data);
}

Security Best Practices

Keep your API key secure! Never expose it in client-side code, public repositories, or logs.

✅ Do This

  • Store API keys in environment variables
  • Use server-side configurations
  • Rotate keys regularly
  • Monitor API key usage
  • Implement proper error handling

❌ Don’t Do This

  • Hard-code API keys in source code
  • Commit API keys to version control
  • Share API keys in plain text
  • Use the same key across all environments
  • Ignore authentication errors

Environment Variables

Store your API key securely using environment variables:
.env
CSC_API_KEY=your_api_key_here
app.js
const apiKey = process.env.CSC_API_KEY;

const response = await fetch('https://api.countrystatecity.in/v1/countries', {
  headers: { 'X-CSCAPI-KEY': apiKey }
});

Authentication Errors

When authentication fails, the API returns a 401 Unauthorized status with an error message:
curl -X GET 'https://api.countrystatecity.in/v1/countries' \
  -H 'X-CSCAPI-KEY: invalid_key'
{
  "error": "Unauthorized. You shouldn't be here."
}

Common Authentication Issues

Cause: Invalid, missing, or expired API keySolution:
  • Verify your API key is correct
  • Check the header name is exactly X-CSCAPI-KEY
  • Ensure the key hasn’t been revoked
  • Register for a new key if needed
Cause: HTTP client configuration issuesSolution:
  • Verify headers are properly set
  • Check for typos in header name
  • Ensure headers aren’t being stripped by proxies
  • Test with a simple cURL command first
Cause: Browser blocking cross-origin requestsSolution:
  • Make API calls from your server instead
  • Use a proxy server for development
  • Never use API keys in browser applications

Testing Your Authentication

Use this simple test to verify your API key is working:
curl -X GET 'https://api.countrystatecity.in/v1/countries' \
  -H 'X-CSCAPI-KEY: YOUR_API_KEY' \
  -w "HTTP Status: %{http_code}\n"
A successful authentication test should return HTTP 200 with a list of countries. If you get different results, check your API key and request format.