Open Source Developer Tools 1 vues

dr5hn/countries-states-cities-database: A 250-Country Dataset in 12 Formats

M
Mohamed IDBRAHIM
Auteur
dr5hn/countries-states-cities-database: A 250-Country Dataset in 12 Formats

Every application that touches geography faces the same friction: where do you get reliable, structured location data that stays current? Commercial datasets lock you into expensive contracts. Scraping Wikipedia breaks the moment a page redesigns. Maintaining your own hierarchy of countries, states, cities, and postcodes becomes a part-time job that distracts from actual product work.

The dr5hn/countries-states-cities-database project exists to remove that friction. With 9,719 GitHub stars, 3,012 forks, and a last commit dated July 13, 2026, it is one of the most actively maintained open-source geographic datasets available. This article breaks down what the dataset contains, how to integrate it, and when to choose its managed API over self-hosting.


What is dr5hn/countries-states-cities-database?

dr5hn/countries-states-cities-database is a community-maintained, comprehensive dataset of global administrative divisions—countries, states/regions, cities, and postcodes—published under the Open Database License (ODbL v1.0). The project is maintained by Darshan Gada (@dr5hn) and contributors, with the primary implementation language being Python↗ Bright Coding Blog.

The dataset's scale is substantial: 250 countries, 5,299 states/regions/municipalities, 153,765 cities/towns/districts, and 844,248 postcodes across 125 countries. Timezone coverage claims 100% IANA compliance with 427 total timezones. Country and state names are available in 19 languages including native scripts.

What distinguishes this project from static CSV dumps is its multi-format publishing pipeline. Every release generates exports in 12 formats: JSON, MySQL↗ Bright Coding Blog, PostgreSQL↗ Bright Coding Blog, SQLite, SQL Server, MongoDB, XML, YAML, CSV, GeoJSON, TOON (a token-optimized format for LLM contexts, ~40% fewer tokens than JSON), and Parquet (columnar, analytics-ready). The README documents export times and sizes: CSV exports in 1 second at 40 MB (9 MB compressed), while SQLite takes 45 seconds at 89 MB uncompressed.

The project supports its ecosystem through two managed products: a REST API (api.countrystatecity.in) and a browser-based Export Tool (export.countrystatecity.in). These fund ongoing maintenance and offer faster paths to production than manual dataset management.


Key Features

Validated relational structure with foreign keys. Every contribution is checked for referential integrity. Cities link to states via state_id and state_code; states link to countries via country_id and country_code. This prevents orphaned records that plague loosely assembled geographic datasets.

Multi-format distribution with compression. The GitHub Releases page ships every format as gzipped assets. JSON—the largest at 271 MB uncompressed, 18 MB compressed—exports in 4 seconds. Parquet, optimized for analytics workloads, exports in 7 seconds at 31 MB (27 MB compressed). For LLM applications, TOON format reduces token count by approximately 40% compared to JSON while maintaining the same semantic structure.

Managed API with tiered access. The REST API supports querying nested resources: /countries/{iso2}/states/{state_code}/cities returns filtered city lists without downloading the full dataset. A free tier exists for prototyping; paid tiers handle production traffic. The API publishes an OpenAPI specification and maintains a status page.

Browser-based export customization. The Export Tool lets you select specific countries, regions, output formats, and field subsets before downloading. This avoids the common problem of importing 250 countries when your application only needs Southeast Asia.

Language and localization support. Beyond English names, the dataset includes native script representations and translations across 19 languages. This matters for applications displaying location names to local users without separate localization pipelines.

Postcode coverage for 125 countries. With 844,248 postcodes, the dataset supports address validation and geocoding workflows that simpler country-state-city hierarchies cannot.


Use Cases

E-commerce checkout and shipping. Address forms require cascading dropdowns: country selection filters states, state selection filters cities. The dataset's validated foreign keys and multiple formats (JSON for frontend APIs, SQL for backend databases) fit naturally into this flow. Postcode data enables shipping cost calculation and address verification.

Analytics and business intelligence. The Parquet export loads directly into Pandas, Polars, or data warehouses. IANA timezone coverage supports temporal analysis—correlating events with local time rather than UTC offsets that change with daylight saving rules.

Machine learning and NLP. The TOON format's token efficiency makes it suitable for fine-tuning or prompting LLMs with structured geographic knowledge. Native script names and multilingual support enable training on non-English location references.

Travel and hospitality applications. Hotel booking engines, flight search, and itinerary builders need consistent location hierarchies. The 19-language support and timezone data cover the requirements without custom data engineering.

Government and NGO reporting. The ODbL license permits modification and redistribution with attribution, fitting organizations that need transparent data provenance and cannot rely on proprietary sources.


Installation & Setup

Direct Download (Fastest for Static Data)

Download the latest gzipped release without cloning the repository:

# Download JSON cities export
curl -LO https://github.com/dr5hn/countries-states-cities-database/releases/latest/download/json-cities.json.gz

# Decompress
gunzip json-cities.json.gz

The -L flag follows GitHub's redirect to the actual release asset. The --depth 1 clone mentioned in the README avoids downloading full git history:

# Clone only the latest commit for reference files
git clone --depth 1 https://github.com/dr5hn/countries-states-cities-database.git

Reference files (countries, states, schema definitions) live in the repository. Full dataset exports are release assets only.

NPM Packages (JavaScript↗ Bright Coding Blog/TypeScript)

Install scoped packages for specific data types:

# Core countries data
npm install @countrystatecity/countries

# Browser-optimized version
npm install @countrystatecity/countries-browser

# Additional modules as needed
npm install @countrystatecity/currencies
npm install @countrystatecity/timezones
npm install @countrystatecity/translations
npm install @countrystatecity/cli

PyPI Packages (Python)

# Core countries package
pip install countrystatecity-countries

# Additional modules
pip install countrystatecity-timezones
pip install countrystatecity-currencies
pip install countrystatecity-translations
pip install countrystatecity-phonecodes

REST API Setup

Obtain an API key from countrystatecity.in, then:

# Store key in environment
export CSCAPI_KEY="your_key_here"

# Query cities in Maharashtra, India
curl https://api.countrystatecity.in/v1/countries/IN/states/MH/cities \
  -H "X-CSCAPI-KEY: $CSCAPI_KEY"

The IN and MH codes are ISO2 country and state codes respectively—standard identifiers that integrate with other geographic services.


Real Code Examples

The README provides two primary code demonstrations. These are reproduced exactly with explanatory context.

Example 1: REST API Query

# Query all cities in Maharashtra, India using ISO2 codes
curl https://api.countrystatecity.in/v1/countries/IN/states/MH/cities \
  -H "X-CSCAPI-KEY: $YOUR_API_KEY"

Explanation: This endpoint demonstrates the API's nested resource design. The path structure /countries/{iso2}/states/{state_code}/cities mirrors the dataset's relational hierarchy. The X-CSCAPI-KEY header authenticates the request. Replace $YOUR_API_KEY with your actual key, or export it as shown in the Installation section. The response returns a JSON array of city objects with id, name, latitude, longitude, and timezone fields.

When to use this: Real-time applications where downloading the full 271 MB JSON dataset is impractical. Mobile apps, serverless functions, and client-side JavaScript benefit from API queries that return only needed data.

Example 2: Direct File Download

# Download latest JSON cities export from GitHub Releases
curl -LO https://github.com/dr5hn/countries-states-cities-database/releases/latest/download/json-cities.json.gz

# Decompress for use
gunzip json-cities.json.gz

Explanation: The -L flag handles GitHub's release asset redirect. The -O (combined as -LO) saves with the remote filename. The latest URL alias always resolves to the most recent release—useful for automated pipelines. After gunzip, you have a 271 MB JSON file suitable for import into document databases or processing with jq, Python's json module, or streaming parsers for memory-constrained environments.

When to use this: Batch processing, offline applications, or when you need the full dataset for joins and complex filtering that would require multiple API calls. The compressed 18 MB transfer is efficient for CI/CD caches or Docker↗ Bright Coding Blog image layers.

Example 3: Contribution Format (JSON Schema)

{
  "name": "San Francisco",
  "state_id": 1416,
  "state_code": "CA",
  "country_id": 233,
  "country_code": "US",
  "latitude": "37.77493",
  "longitude": "-122.41942",
  "timezone": "America/Los_Angeles",
  "wikiDataId": "Q62"
}

Explanation: This example from the contribution guidelines shows the required and optional fields for new city submissions. Required: name, state_id, state_code, country_id, country_code, latitude, longitude. Optional: timezone, wikiDataId, native. Auto-managed (omit): id, created_at, updated_at, flag. The wikiDataId links to Wikidata for disambiguation and cross-referencing. Contributors submit via the Community Manager web UI or direct JSON edits under contributions/cities/.


Advanced Usage & Best Practices

Format selection by workload. The README's export table reveals clear trade-offs. For analytical queries, Parquet's columnar structure outperforms JSON by orders of magnitude. For LLM context windows, TOON's ~40% token reduction directly translates to cost savings and longer possible prompts. For universal compatibility, CSV remains the safest interchange format at 1-second export time.

Avoid editing generated directories. The json/, csv/, xml/, yml/, sql/, and other format directories are rebuilt from MySQL on every release. Edits here will be overwritten. Direct contributions to contributions/cities/, contributions/states/, contributions/countries/, or contributions/postcodes/ are the correct path.

API vs. self-hosted decision framework. Choose the REST API when: you need real-time data without version management, traffic is variable, or you want automatic updates without release monitoring. Choose direct downloads when: you operate offline, have strict latency requirements, need custom indexing, or want to avoid ongoing API costs at scale.

Attribution compliance. The ODbL requires visible attribution. Include the specified text in your application's about page, documentation, or data credits:

Data by Countries States Cities Database
https://github.com/dr5hn/countries-states-cities-database | ODbL v1.0

Derivatives must be shared under the same license—plan accordingly if you modify and redistribute the dataset.


Comparison with Alternatives

Feature dr5hn/countries-states-cities-database GeoNames Natural Earth
License ODbL v1.0 (attribution required) Creative Commons Attribution Public Domain
Formats 12 (incl. Parquet, TOON, GeoJSON) Tab-delimited, various APIs Shapefile, GeoJSON, SQLite
Postcodes 844,248 (125 countries) Limited, variable coverage None
Timezones 100% IANA (427 zones) Partial None
Languages 19 + native scripts Primarily English Primarily English
Managed API Yes (tiered pricing) Yes (web services, credits) No
Community contribution Web UI + PR Forum-based Limited
Primary language Python (data pipeline) Java (web services) —

GeoNames offers broader feature types (mountains, airports, populated places) but lacks the structured country-state-city hierarchy and multi-format exports. Its web service requires credit-based pricing for commercial use. Natural Earth excels at cartographic visualization with cultural and physical vector data but provides no postcode or timezone coverage and no API. The dr5hn project occupies a specific niche: structured administrative hierarchies with rich localization, ready for application integration rather than GIS visualization.


FAQ

Q: Can I use this commercially? A: Yes, under ODbL v1.0. Attribution is required; derivatives must share alike.

Q: How current is the data? A: Last updated July 11, 2026 per README. Check release dates for specific exports.

Q: What's the fastest way to get started? A: The REST API free tier or curl download of a gzipped release.

Q: Do I need to clone the full repository? A: No. Use git clone --depth 1 for reference files, or download release assets directly.

Q: Which format should I choose? A: JSON for flexibility, Parquet for analytics, SQL for relational databases, TOON for LLM contexts.

Q: How do I report data errors? A: Use the Community Manager web UI or open a GitHub issue.

Q: Is there a rate limit on the free API tier? A: The README does not specify limits; check countrystatecity.in for current tier details.


Conclusion

The dr5hn/countries-states-cities-database project solves a genuinely tedious problem with engineering discipline: validated data, multiple export formats, and sustainable funding through managed services. Its 9,719 stars reflect real developer adoption, not marketing momentum.

This dataset fits teams that need reliable geographic hierarchies without building a data pipeline from scratch. The REST API suits rapid prototyping and serverless architectures; direct downloads serve data-intensive or offline applications. The ODbL license keeps options open while requiring proper attribution.

If your application handles addresses, location search, timezone-aware scheduling, or geographic analytics, evaluate this dataset against your latency, licensing, and maintenance constraints. The GitHub repository contains the latest releases, contribution guidelines, and issue tracker. For managed access, start with the API playground to test queries against your specific use case.

For related geographic data processing techniques, see [INTERNAL_LINK: working-with-parquet-files-in-python] or [INTERNAL_LINK: open-data-licenses-guide].

Commentaires 0

Aucun commentaire pour l'instant. Soyez le premier à réagir !

Laisser un commentaire