API Documentation - Endpoints & Examples

All data from a state

Overview

This endpoint retrieves comprehensive data for a specific state, including all cities and postal codes within that state. Use this when you need detailed information about a particular state by its ID or name.

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/states

Returns all data from that state.

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
state required, id or string State ID or state name
limitToken optional, number 1000 (default). Maximum number of tokens you want to spend on this request
fields optional, string id,lang,state_name (default). Expected fields in the response
lang optional, lang en (default). Expected language of 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/states';

async function getStateData(stateName) {
  try {
    const params = new URLSearchParams({
      apikey: API_KEY,
      state: stateName,
      lang: 'en',
      fields: 'id,state_name,lang,state_cities'
    });

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

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

    const stateData = await response.json();
    console.log('State Data:', stateData);
    return stateData;
  } catch (error) {
    console.error('Error fetching state data:', error);
    throw error;
  }
}

// Usage
getStateData('California');
// Or by ID
getStateData('8dd25479-067a-43b0-ac4a-8e7faf2bcafb');

JavaScript (Axios)

import axios from 'axios';

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

async function getStateData(stateName) {
  try {
    const response = await axios.get(BASE_URL, {
      params: {
        apikey: API_KEY,
        state: stateName,
        lang: 'en',
        fields: 'id,state_name,lang,state_cities'
      }
    });

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

// Usage
getStateData('Texas');

React

import { useState, useEffect } from 'react';

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

function StateDetails({ stateName }) {
  const [stateData, setStateData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchStateData = async () => {
      if (!stateName) return;

      try {
        setLoading(true);
        const params = new URLSearchParams({
          apikey: API_KEY,
          state: stateName,
          lang: 'en',
          fields: 'id,state_name,lang,state_cities'
        });

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

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

        const data = await response.json();
        setStateData(data[0]);
      } catch (err) {
        setError(err.message);
      } finally {
        setLoading(false);
      }
    };

    fetchStateData();
  }, [stateName]);

  if (loading) return <div>Loading state data...</div>;
  if (error) return <div>Error: {error}</div>;
  if (!stateData) return <div>No data found</div>;

  return (
    <div>
      <h2>{stateData.state_name}</h2>
      <p>ID: {stateData.id}</p>
      {stateData.state_cities && (
        <div>
          <h3>Cities ({stateData.state_cities.length})</h3>
          <ul>
            {stateData.state_cities.map((city) => (
              <li key={city.id}>{city.city_name}</li>
            ))}
          </ul>
        </div>
      )}
    </div>
  );
}

export default StateDetails;

Vue 3

<template>
  <div>
    <div v-if="loading">Loading state data...</div>
    <div v-else-if="error">Error: {{ error }}</div>
    <div v-else-if="stateData">
      <h2>{{ stateData.state_name }}</h2>
      <p>ID: {{ stateData.id }}</p>
      <div v-if="stateData.state_cities">
        <h3>Cities ({{ stateData.state_cities.length }})</h3>
        <ul>
          <li v-for="city in stateData.state_cities" :key="city.id">
            {{ city.city_name }}
          </li>
        </ul>
      </div>
    </div>
    <div v-else>No data found</div>
  </div>
</template>

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

const props = defineProps({
  stateName: {
    type: String,
    required: true
  }
});

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

const stateData = ref(null);
const loading = ref(true);
const error = ref(null);

const fetchStateData = async () => {
  if (!props.stateName) return;

  try {
    loading.value = true;
    error.value = null;

    const params = new URLSearchParams({
      apikey: API_KEY,
      state: props.stateName,
      lang: 'en',
      fields: 'id,state_name,lang,state_cities'
    });

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

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

    const data = await response.json();
    stateData.value = data[0];
  } catch (err) {
    error.value = err.message;
  } finally {
    loading.value = false;
  }
};

watch(() => props.stateName, fetchStateData);
onMounted(fetchStateData);
</script>

Angular

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

interface City {
  id: string;
  city_name: string;
}

interface State {
  id: string;
  state_name: string;
  lang: string;
  state_cities?: City[];
  state_zip_codes?: string[];
}

@Component({
  selector: 'app-state-details',
  standalone: true,
  imports: [CommonModule],
  template: `
    <div>
      <div *ngIf="loading">Loading state data...</div>
      <div *ngIf="error">Error: {{ error }}</div>
      <div *ngIf="!loading && !error && stateData">
        <h2>{{ stateData.state_name }}</h2>
        <p>ID: {{ stateData.id }}</p>
        <div *ngIf="stateData.state_cities">
          <h3>Cities ({{ stateData.state_cities.length }})</h3>
          <ul>
            <li *ngFor="let city of stateData.state_cities">
              {{ city.city_name }}
            </li>
          </ul>
        </div>
      </div>
    </div>
  `
})
export class StateDetailsComponent implements OnInit, OnChanges {
  @Input() stateName!: string;

  private readonly API_KEY = 'YOUR_API_KEY';
  private readonly BASE_URL = 'https://api.countrydataapi.com/v1/states';

  stateData: State | null = null;
  loading = true;
  error: string | null = null;

  constructor(private http: HttpClient) {}

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

  ngOnChanges(): void {
    this.fetchStateData();
  }

  private fetchStateData(): void {
    if (!this.stateName) return;

    this.loading = true;
    this.error = null;

    const params = new HttpParams()
      .set('apikey', this.API_KEY)
      .set('state', this.stateName)
      .set('lang', 'en')
      .set('fields', 'id,state_name,lang,state_cities');

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

PHP

<?php

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

function getStateData($stateName, $apiKey) {
    $baseUrl = 'https://api.countrydataapi.com/v1/states';

    $params = http_build_query([
        'apikey' => $apiKey,
        'state' => $stateName,
        'lang' => 'en',
        'fields' => 'id,state_name,lang,state_cities'
    ]);

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

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    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);
}

// Usage
try {
    $stateData = getStateData('California', $apiKey);

    if (!empty($stateData)) {
        $state = $stateData[0];
        echo "State: " . $state['state_name'] . "\n";
        echo "ID: " . $state['id'] . "\n";

        if (isset($state['state_cities'])) {
            echo "Cities:\n";
            foreach ($state['state_cities'] as $city) {
                echo "  - " . $city['city_name'] . "\n";
            }
        }
    }
} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
}
?>

Python

import requests

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

def get_state_data(state_name):
    """Fetch detailed data for a specific state."""
    params = {
        'apikey': API_KEY,
        'state': state_name,
        'lang': 'en',
        'fields': 'id,state_name,lang,state_cities'
    }

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

        state_data = response.json()
        return state_data[0] if state_data else None
    except requests.exceptions.RequestException as e:
        print(f'Error fetching state data: {e}')
        raise

# Usage
if __name__ == '__main__':
    state = get_state_data('California')

    if state:
        print(f"State: {state['state_name']}")
        print(f"ID: {state['id']}")

        if 'state_cities' in state:
            print(f"Cities ({len(state['state_cities'])}):")
            for city in state['state_cities'][:5]:  # First 5 cities
                print(f"  - {city['city_name']}")


# Async version with aiohttp
import aiohttp
import asyncio

async def get_state_data_async(state_name):
    """Fetch state data asynchronously."""
    params = {
        'apikey': API_KEY,
        'state': state_name,
        'lang': 'en',
        'fields': 'id,state_name,lang,state_cities'
    }

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

# Usage
# state = asyncio.run(get_state_data_async('Texas'))

cURL

# Basic request by state name
curl -X GET "https://api.countrydataapi.com/v1/states?apikey=YOUR_API_KEY&state=California&lang=en&fields=id,state_name,lang,state_cities"

# Request by state ID
curl -X GET "https://api.countrydataapi.com/v1/states?apikey=YOUR_API_KEY&state=8dd25479-067a-43b0-ac4a-8e7faf2bcafb&lang=en"

# With pretty-printed JSON output
curl -X GET "https://api.countrydataapi.com/v1/states?apikey=YOUR_API_KEY&state=Texas&lang=en" | json_pp

# Include zip codes (ADVANCED request)
curl -X GET "https://api.countrydataapi.com/v1/states?apikey=YOUR_API_KEY&state=Colorado&fields=id,state_name,state_cities,state_zip_codes"

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

Error Handling

The API may return the following error responses:

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

Error Response Example

{
  "statusCode": 404,
  "message": "State not found",
  "error": "Not Found"
}