API Documentation - Endpoints & Examples

All data from a state

Overview

This endpoint returns a comprehensive list of all states available in the CountryDataAPI database. It provides detailed information about states worldwide, making it ideal for applications that need to display or process state-level geographical data.

Country Data API provides detailed information about +200 different countries

Authentication

All API requests require authentication using an API key. Include your API key as a query parameter in each request:

?apikey=YOUR_API_KEY

You can obtain an API key by registering at CountryDataAPI.


Request

HTTP GET

https://api.countrydataapi.com/v1/state/all

Returns a list of all states

According to the requested fields, there will be 3 types of requests:

  • BASIC: Returns the fields id, state_name, lang Each state will cost 1 token

  • NORMAL: Returns the field state_cities [All IDs and names of cities in the state] Each city will cost 1 token

  • ADVANCED: Returns the field state_zip_codes [All postal codes of the city] Each postal code costs 1 token

Query Params


Parameter Type Description
apikey required, token Account authentication key
lang optional, lang en (default). Expected language of the response
limitToken optional, number 1000 (default). Maximum number of tokens you want to spend on this request
limitStates optional, number 10 (default). Maximum number of states you want to return
fields optional, string id,lang,state_name (default). Expected fields in the response

Response

Sample Response

[
  {
    "id": "8dd25479-067a-43b0-ac4a-8e7faf2bcafb",
    "state_name": "Takhar",
    "lang": "en",
    "state_cities": [
      {
        "id": "8dd25476-067a-43b0-ac4b-8e7faf2bcbfb",
        "city_name": "City"
      }
    ],
    "state_zip_codes": [
      "00000",
      "00001"
    ]
  }
]

Code Examples

JavaScript (Fetch)

const API_KEY = 'YOUR_API_KEY';
const BASE_URL = 'https://api.countrydataapi.com/v1/state/all';

async function getAllStates() {
  try {
    const params = new URLSearchParams({
      apikey: API_KEY,
      lang: 'en',
      limitStates: '10',
      fields: 'id,state_name,lang'
    });

    const response = await fetch(`${BASE_URL}?${params}`);

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

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

// Usage
getAllStates();

JavaScript (Axios)

import axios from 'axios';

const API_KEY = 'YOUR_API_KEY';
const BASE_URL = 'https://api.countrydataapi.com/v1/state/all';

async function getAllStates() {
  try {
    const response = await axios.get(BASE_URL, {
      params: {
        apikey: API_KEY,
        lang: 'en',
        limitStates: 10,
        fields: 'id,state_name,lang'
      }
    });

    console.log('States:', response.data);
    return response.data;
  } catch (error) {
    if (axios.isAxiosError(error)) {
      console.error('API Error:', error.response?.data || error.message);
    }
    throw error;
  }
}

// Usage
getAllStates();

React

import { useState, useEffect } from 'react';

const API_KEY = 'YOUR_API_KEY';
const BASE_URL = 'https://api.countrydataapi.com/v1/state/all';

function StatesList() {
  const [states, setStates] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchStates = async () => {
      try {
        const params = new URLSearchParams({
          apikey: API_KEY,
          lang: 'en',
          limitStates: '10',
          fields: 'id,state_name,lang'
        });

        const response = await fetch(`${BASE_URL}?${params}`);

        if (!response.ok) {
          throw new Error('Failed to fetch states');
        }

        const data = await response.json();
        setStates(data);
      } catch (err) {
        setError(err.message);
      } finally {
        setLoading(false);
      }
    };

    fetchStates();
  }, []);

  if (loading) return <div>Loading states...</div>;
  if (error) return <div>Error: {error}</div>;

  return (
    <div>
      <h2>All States</h2>
      <ul>
        {states.map((state) => (
          <li key={state.id}>{state.state_name}</li>
        ))}
      </ul>
    </div>
  );
}

export default StatesList;

Vue 3

<template>
  <div>
    <h2>All States</h2>
    <div v-if="loading">Loading states...</div>
    <div v-else-if="error">Error: {{ error }}</div>
    <ul v-else>
      <li v-for="state in states" :key="state.id">
        {{ state.state_name }}
      </li>
    </ul>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';

const API_KEY = 'YOUR_API_KEY';
const BASE_URL = 'https://api.countrydataapi.com/v1/state/all';

const states = ref([]);
const loading = ref(true);
const error = ref(null);

const fetchStates = async () => {
  try {
    const params = new URLSearchParams({
      apikey: API_KEY,
      lang: 'en',
      limitStates: '10',
      fields: 'id,state_name,lang'
    });

    const response = await fetch(`${BASE_URL}?${params}`);

    if (!response.ok) {
      throw new Error('Failed to fetch states');
    }

    states.value = await response.json();
  } catch (err) {
    error.value = err.message;
  } finally {
    loading.value = false;
  }
};

onMounted(fetchStates);
</script>

Angular

import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { CommonModule } from '@angular/common';

interface State {
  id: string;
  state_name: string;
  lang: string;
  state_cities?: Array<{ id: string; city_name: string }>;
  state_zip_codes?: string[];
}

@Component({
  selector: 'app-states-list',
  standalone: true,
  imports: [CommonModule],
  template: `
    <div>
      <h2>All States</h2>
      <div *ngIf="loading">Loading states...</div>
      <div *ngIf="error">Error: {{ error }}</div>
      <ul *ngIf="!loading && !error">
        <li *ngFor="let state of states">{{ state.state_name }}</li>
      </ul>
    </div>
  `
})
export class StatesListComponent implements OnInit {
  private readonly API_KEY = 'YOUR_API_KEY';
  private readonly BASE_URL = 'https://api.countrydataapi.com/v1/state/all';

  states: State[] = [];
  loading = true;
  error: string | null = null;

  constructor(private http: HttpClient) {}

  ngOnInit(): void {
    this.fetchStates();
  }

  private fetchStates(): void {
    const params = new HttpParams()
      .set('apikey', this.API_KEY)
      .set('lang', 'en')
      .set('limitStates', '10')
      .set('fields', 'id,state_name,lang');

    this.http.get<State[]>(this.BASE_URL, { params }).subscribe({
      next: (data) => {
        this.states = data;
        this.loading = false;
      },
      error: (err) => {
        this.error = err.message;
        this.loading = false;
      }
    });
  }
}

PHP

<?php

$apiKey = 'YOUR_API_KEY';
$baseUrl = 'https://api.countrydataapi.com/v1/state/all';

$params = http_build_query([
    'apikey' => $apiKey,
    'lang' => 'en',
    'limitStates' => 10,
    'fields' => 'id,state_name,lang'
]);

$url = $baseUrl . '?' . $params;

$options = [
    'http' => [
        'method' => 'GET',
        'header' => 'Content-Type: application/json'
    ]
];

$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);

if ($response === false) {
    die('Error fetching states');
}

$states = json_decode($response, true);

foreach ($states as $state) {
    echo "State: " . $state['state_name'] . "\n";
}

// Using cURL
function getAllStatesWithCurl($apiKey) {
    $baseUrl = 'https://api.countrydataapi.com/v1/state/all';

    $params = http_build_query([
        'apikey' => $apiKey,
        'lang' => 'en',
        'limitStates' => 10,
        'fields' => 'id,state_name,lang'
    ]);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $baseUrl . '?' . $params);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($httpCode !== 200) {
        throw new Exception("HTTP Error: $httpCode");
    }

    return json_decode($response, true);
}
?>

Python

import requests

API_KEY = 'YOUR_API_KEY'
BASE_URL = 'https://api.countrydataapi.com/v1/state/all'

def get_all_states():
    """Fetch all states from the CountryDataAPI."""
    params = {
        'apikey': API_KEY,
        'lang': 'en',
        'limitStates': 10,
        'fields': 'id,state_name,lang'
    }

    try:
        response = requests.get(BASE_URL, params=params)
        response.raise_for_status()

        states = response.json()
        return states
    except requests.exceptions.RequestException as e:
        print(f'Error fetching states: {e}')
        raise

# Usage
if __name__ == '__main__':
    states = get_all_states()
    for state in states:
        print(f"State: {state['state_name']}")


# Async version with aiohttp
import aiohttp
import asyncio

async def get_all_states_async():
    """Fetch all states asynchronously."""
    params = {
        'apikey': API_KEY,
        'lang': 'en',
        'limitStates': 10,
        'fields': 'id,state_name,lang'
    }

    async with aiohttp.ClientSession() as session:
        async with session.get(BASE_URL, params=params) as response:
            if response.status == 200:
                return await response.json()
            else:
                raise Exception(f'HTTP Error: {response.status}')

# Usage
# asyncio.run(get_all_states_async())

cURL

# Basic request
curl -X GET "https://api.countrydataapi.com/v1/state/all?apikey=YOUR_API_KEY&lang=en&limitStates=10&fields=id,state_name,lang"

# With pretty-printed JSON output
curl -X GET "https://api.countrydataapi.com/v1/state/all?apikey=YOUR_API_KEY&lang=en&limitStates=10&fields=id,state_name,lang" | json_pp

# With headers shown
curl -v -X GET "https://api.countrydataapi.com/v1/state/all?apikey=YOUR_API_KEY&lang=en&limitStates=10"

# Save response to file
curl -X GET "https://api.countrydataapi.com/v1/state/all?apikey=YOUR_API_KEY&lang=en&limitStates=10" -o states.json

Error Handling

The API may return the following error responses:

Status Code Description
400 Bad Request - Invalid parameters
401 Unauthorized - Invalid or missing API key
403 Forbidden - Insufficient permissions or token balance
429 Too Many Requests - Rate limit exceeded
500 Internal Server Error

Error Response Example

{
  "statusCode": 401,
  "message": "Invalid API key",
  "error": "Unauthorized"
}