SDKs overview
CountryStateCity provides developers with tools to integrate its hierarchical geographical data into various applications. The primary mechanism for interaction is a RESTful API, which can be accessed directly via HTTP requests. To streamline this process, CountryStateCity offers an official SDK, specifically for JavaScript environments, which abstracts the underlying API calls and simplifies data retrieval and manipulation within web and Node.js applications. This SDK is designed to facilitate common tasks such as populating dropdowns for country, state, and city selection in user interfaces, validating location inputs, and enriching user data with geographical context CountryStateCity API documentation.
Beyond the official offerings, the API's standard REST architecture allows for integration using standard HTTP client libraries available in virtually any programming language. This flexibility fosters a community-driven approach where developers can create and share their own client libraries or wrappers. These community contributions often cater to specific frameworks or development patterns, expanding the accessibility of CountryStateCity data across a broader range of technology stacks. The API's focus on structured country, state, and city data makes it particularly useful for applications requiring precise geographical segmentation without full address geocoding capabilities.
Official SDKs by language
CountryStateCity maintains one official SDK primarily targeting JavaScript environments, which is suitable for both client-side browser applications and server-side Node.js projects. This SDK is developed and supported by the CountryStateCity team to ensure compatibility and optimal performance with their API. The library encapsulates the necessary logic for authentication, request formatting, and response parsing, reducing the boilerplate code developers need to write.
The official JavaScript SDK is distributed through standard package managers, making it straightforward to include in most modern JavaScript projects. It provides methods to fetch lists of countries, states within a specific country, and cities within a specific state. This structured access aligns with the API's hierarchical data model, which is designed for efficiency in location-based data retrieval.
The table below summarizes the official SDK:
| Language | Package Name | Installation Command | Maturity |
|---|---|---|---|
| JavaScript | country-state-city |
npm install country-state-city or yarn add country-state-city |
Stable |
While the official SDK is JavaScript-centric, the CountryStateCity API can be consumed by any language capable of making HTTP requests. For instance, developers frequently use libraries like requests in Python, Guzzle in PHP, or the built-in fetch API in JavaScript for direct API integration. Code examples for these languages are often provided in the official documentation to guide developers in making direct API calls when an official SDK is not available for their preferred language CountryStateCity developer documentation.
Installation
Installing the official CountryStateCity JavaScript SDK is accomplished using standard package managers. For Node.js projects or front-end frameworks like React, Angular, or Vue.js, npm or yarn are the recommended tools. This process adds the library to your project's dependencies, allowing you to import and use its functionalities.
Using npm:
npm install country-state-city
Using yarn:
yarn add country-state-city
After installation, the library can be imported into your JavaScript files. For ES module environments (common in modern web development), you would use an import statement. For CommonJS environments (typical in older Node.js projects), a require statement would be used.
For direct API consumption without an SDK, no specific installation is required beyond ensuring your development environment has an HTTP client library. Most programming languages offer robust built-in or widely adopted external libraries for this purpose. For example, in a browser environment, the fetch API is globally available and does not require installation Mozilla's guide to the Fetch API.
Quickstart example
This quickstart demonstrates how to use the official JavaScript SDK to fetch a list of countries, then states within a specific country, and finally cities within a specific state. This example assumes you have already installed the country-state-city package as described in the installation section.
JavaScript (using the official SDK):
import { Country, State, City } from 'country-state-city';
// Get all countries
const allCountries = Country.getAllCountries();
console.log('All Countries:', allCountries.map(c => c.name));
// Example: Get states in the United States
const usCountry = allCountries.find(country => country.isoCode === 'US');
if (usCountry) {
const statesInUS = State.getStatesOfCountry(usCountry.isoCode);
console.log(`States in ${usCountry.name}:`, statesInUS.map(s => s.name));
// Example: Get cities in California (CA) within the United States
const californiaState = statesInUS.find(state => state.isoCode === 'CA');
if (californiaState) {
const citiesInCalifornia = City.getCitiesOfState(usCountry.isoCode, californiaState.isoCode);
console.log(`Cities in ${californiaState.name}, ${usCountry.name}:`, citiesInCalifornia.map(city => city.name.slice(0, 20) + '...')); // Truncate for brevity
} else {
console.log('California state not found.');
}
} else {
console.log('United States not found.');
}
// To use with an API key (if applicable for your plan)
// The SDK primarily works with a local dataset or without an explicit API key for basic lookups.
// For direct API calls requiring a key, you would typically use fetch or axios like this:
/*
async function fetchWithApiKey(url) {
const API_KEY = 'YOUR_API_KEY'; // Replace with your actual API key
const headers = {
'X-CSCAPI-KEY': API_KEY
};
try {
const response = await fetch(url, { headers });
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log('API Data:', data);
return data;
} catch (error) {
console.error('Error fetching data:', error);
}
}
// Example: Fetch countries directly from API (if API requires key for this specific endpoint)
// fetchWithApiKey('https://api.countrystatecity.in/v1/countries');
*/
This example demonstrates how to leverage the SDK's methods to retrieve hierarchical location data. The methods Country.getAllCountries(), State.getStatesOfCountry(), and City.getCitiesOfState() provide access to the dataset. For more advanced usage or direct API interactions requiring an API key (especially for higher request volumes beyond the free tier), developers would typically make authenticated HTTP requests as shown in the commented-out section CountryStateCity quickstart guide.
Community libraries
While CountryStateCity provides an official JavaScript SDK, the open nature of its REST API allows and encourages the development of community-contributed libraries and wrappers. These libraries often emerge to serve specific programming languages, frameworks, or development paradigms that are not directly covered by official SDKs. For instance, developers might create wrappers in Python, PHP, Ruby, or Go to integrate CountryStateCity data more idiomatically into their respective ecosystems.
Community libraries can offer several advantages, such as:
- Language-specific idioms: Adapting the API interaction to common patterns and best practices of a particular programming language.
- Framework integration: Providing components or services specifically designed for frameworks like Laravel, Django, Ruby on Rails, or Spring Boot.
- Additional features: Sometimes including caching mechanisms, rate limiting, or error handling tailored to specific use cases.
- Alternative data sources: While the primary API is the source, some community libraries might integrate local datasets for offline use or performance optimization, though this would deviate from real-time API data.
Developers interested in community solutions typically search package repositories (e.g., PyPI for Python, Composer for PHP, RubyGems for Ruby) or platforms like GitHub for projects related to "CountryStateCity API" or "country state city data." It is advisable to review the documentation, community support, and maintenance status of any third-party library before integrating it into a production environment. For example, a Python developer might look for a client library that wraps API calls into Pythonic objects, simplifying data access compared to raw HTTP requests AWS SDKs overview for context on SDK benefits.
As of 2026, while specific widely-adopted community libraries are not officially endorsed or listed by CountryStateCity, the API's standard REST interface means that any HTTP client library can be used. This allows for custom integrations tailored to project requirements, providing flexibility for developers working outside of the JavaScript ecosystem.