Dokumentation

Select States

Bundeslaender/Provinzen nach Land abrufen, optimiert fuer Select-Dropdowns

Der Endpunkt /v1/select/states gibt eine leichtgewichtige Liste von Bundeslaendern/Provinzen gefiltert nach Land zurueck, mit nur den Feldern id und name, optimiert fuer Dropdown-Menues.

Endpunkt

GET https://api.countrydataapi.com/v1/select/states

Authentifizierung

Fuegen Sie Ihren API-Schluessel als Query-Parameter hinzu:

?apikey=ihr-api-schluessel

Ihr API-Schluessel ist wie ein Passwort, halten Sie ihn sicher. Holen Sie sich Ihren Schluessel vom Konto-Dashboard.

Query-Parameter

Parameter Typ Erforderlich Beschreibung
apikey string Ja Ihr API-Authentifizierungsschluessel
country string Ja Land-ID (vom Endpunkt /select/countries)
lang string Nein Sprachcode fuer Bundesland-Namen (Standard: en)

Unterstuetzte Sprachen

  • en - Englisch (Standard)
  • es - Spanisch
  • pt - Portugiesisch
  • fr - Franzoesisch
  • de - Deutsch
  • it - Italienisch

Anfrage-Beispiel

# Bundeslaender fuer Deutschland abrufen
curl "https://api.countrydataapi.com/v1/select/states?apikey=ihr-api-schluessel&country=66c7a6c9e4bda21f4ab10f0d&lang=de"

JavaScript (Fetch)

const API_KEY = 'ihr-api-schluessel';
const COUNTRY_ID = '66c7a6c9e4bda21f4ab10f0d'; // Deutschland

async function bundeslaenderLaden(countryId) {
  const response = await fetch(
    `https://api.countrydataapi.com/v1/select/states?apikey=${API_KEY}&country=${countryId}&lang=de`
  );
  const data = await response.json();
  return data;
}

const bundeslaender = await bundeslaenderLaden(COUNTRY_ID);

JavaScript (Axios)

import axios from 'axios';

const response = await axios.get(
  'https://api.countrydataapi.com/v1/select/states',
  {
    params: {
      apikey: 'ihr-api-schluessel',
      country: '66c7a6c9e4bda21f4ab10f0d',
      lang: 'de',
    },
  }
);

Python

import requests

response = requests.get(
    'https://api.countrydataapi.com/v1/select/states',
    params={
        'apikey': 'ihr-api-schluessel',
        'country': '66c7a6c9e4bda21f4ab10f0d',
        'lang': 'de'
    }
)
data = response.json()

PHP

<?php
$apiKey = 'ihr-api-schluessel';
$countryId = '66c7a6c9e4bda21f4ab10f0d';
$url = "https://api.countrydataapi.com/v1/select/states?apikey={$apiKey}&country={$countryId}&lang=de";

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);

$data = json_decode($response, true);
?>

Angular

// state.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

interface State {
  id: string;
  name: string;
}

interface ApiResponse {
  success: boolean;
  data: State[];
}

@Injectable({
  providedIn: 'root'
})
export class StateService {
  private readonly API_KEY = 'ihr-api-schluessel';
  private readonly BASE_URL = 'https://api.countrydataapi.com/v1';

  constructor(private http: HttpClient) {}

  getStatesByCountry(countryId: string, lang: string = 'de'): Observable<State[]> {
    const params = new HttpParams()
      .set('apikey', this.API_KEY)
      .set('country', countryId)
      .set('lang', lang);

    return this.http.get<ApiResponse>(
      `${this.BASE_URL}/select/states`,
      { params }
    ).pipe(
      map(response => response.data)
    );
  }
}

// state-select.component.ts
import { Component, Input, Output, EventEmitter, OnChanges, SimpleChanges } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { StateService } from './state.service';

@Component({
  selector: 'app-state-select',
  standalone: true,
  imports: [CommonModule, FormsModule],
  template: `
    <div *ngIf="loading">Bundeslaender werden geladen...</div>
    <div *ngIf="error" class="error">{{ error }}</div>
    <select
      *ngIf="!loading && !error"
      [(ngModel)]="selectedState"
      (ngModelChange)="onStateChange($event)"
      [disabled]="!countryId"
    >
      <option value="">Bundesland auswaehlen...</option>
      <option *ngFor="let state of states" [value]="state.id">
        {{ state.name }}
      </option>
    </select>
  `
})
export class StateSelectComponent implements OnChanges {
  @Input() countryId: string = '';
  @Output() stateChange = new EventEmitter<string>();

  states: any[] = [];
  selectedState = '';
  loading = false;
  error: string | null = null;

  constructor(private stateService: StateService) {}

  ngOnChanges(changes: SimpleChanges) {
    if (changes['countryId'] && this.countryId) {
      this.loadStates();
    } else {
      this.states = [];
      this.selectedState = '';
    }
  }

  loadStates() {
    this.loading = true;
    this.error = null;

    this.stateService.getStatesByCountry(this.countryId, 'de').subscribe({
      next: (data) => {
        this.states = data;
        this.loading = false;
      },
      error: (err) => {
        this.error = 'Fehler beim Laden der Bundeslaender';
        this.loading = false;
      }
    });
  }

  onStateChange(stateId: string) {
    this.stateChange.emit(stateId);
  }
}

Antwort-Format

Erfolgreiche Antwort (Deutschland)

{
  "success": true,
  "data": [
    {
      "id": "66c7a6cae4bda21f4ab11d16",
      "name": "Baden-Wuerttemberg"
    },
    {
      "id": "66c7a6cae4bda21f4ab11d17",
      "name": "Bayern"
    },
    {
      "id": "66c7a6cae4bda21f4ab11d18",
      "name": "Berlin"
    },
    {
      "id": "66c7a6cae4bda21f4ab11d19",
      "name": "Brandenburg"
    },
    {
      "id": "66c7a6cae4bda21f4ab11d1a",
      "name": "Bremen"
    }
    // ... 16 Bundeslaender insgesamt
  ]
}

Antwort-Felder

Feld Typ Beschreibung
success boolean Zeigt an, ob die Anfrage erfolgreich war
data array Array von Bundesland/Provinz-Objekten
data[].id string Eindeutige Bundesland-Kennung (MongoDB ObjectId)
data[].name string Bundesland/Provinz-Name in der angeforderten Sprache

Fehler-Antwort

{
  "success": false,
  "error": {
    "code": "MISSING_PARAMETER",
    "message": "Erforderlicher Parameter 'country' fehlt"
  }
}

Leeres Ergebnis

Wenn ein Land keine Bundeslaender hat (z.B. kleine Laender):

{
  "success": true,
  "data": []
}

Token-Verbrauch

Dieser Endpunkt verbraucht 1 Token pro Anfrage.

Tipp: Speichern Sie Bundesland-Daten nach Land-ID zwischen, um API-Aufrufe zu reduzieren, wenn Benutzer vor und zurueck navigieren.

Kaskadierende Dropdown-Beispiel

HTML

<select id="country" onchange="bundeslaenderLaden(this.value)">
  <option value="">Land auswaehlen...</option>
  <!-- Befuellt von /select/countries -->
</select>

<select id="state" disabled>
  <option value="">Bundesland auswaehlen...</option>
</select>

<script>
const API_KEY = 'ihr-api-schluessel';

async function bundeslaenderLaden(countryId) {
  const stateSelect = document.getElementById('state');

  // Zuruecksetzen und deaktivieren
  stateSelect.innerHTML = '<option value="">Wird geladen...</option>';
  stateSelect.disabled = true;

  if (!countryId) {
    stateSelect.innerHTML = '<option value="">Bundesland auswaehlen...</option>';
    return;
  }

  try {
    const response = await fetch(
      `https://api.countrydataapi.com/v1/select/states?apikey=${API_KEY}&country=${countryId}&lang=de`
    );
    const { success, data, error } = await response.json();

    if (!success) {
      console.error('API-Fehler:', error);
      stateSelect.innerHTML = '<option value="">Fehler beim Laden der Bundeslaender</option>';
      return;
    }

    stateSelect.innerHTML = '<option value="">Bundesland auswaehlen...</option>';
    data.forEach(state => {
      stateSelect.add(new Option(state.name, state.id));
    });
    stateSelect.disabled = false;
  } catch (err) {
    console.error('Netzwerk-Fehler:', err);
    stateSelect.innerHTML = '<option value="">Fehler beim Laden der Bundeslaender</option>';
  }
}
</script>

React-Komponente

import { useState, useEffect } from 'react';

function StateSelect({ countryId, onChange }) {
  const [states, setStates] = useState([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (!countryId) {
      setStates([]);
      return;
    }

    setLoading(true);
    fetch(
      `https://api.countrydataapi.com/v1/select/states?apikey=ihr-api-schluessel&country=${countryId}&lang=de`
    )
      .then(res => res.json())
      .then(({ data }) => {
        setStates(data || []);
        setLoading(false);
      })
      .catch(err => {
        console.error(err);
        setLoading(false);
      });
  }, [countryId]);

  return (
    <select onChange={e => onChange(e.target.value)} disabled={!countryId || loading}>
      <option value="">
        {loading ? 'Wird geladen...' : 'Bundesland auswaehlen...'}
      </option>
      {states.map(state => (
        <option key={state.id} value={state.id}>
          {state.name}
        </option>
      ))}
    </select>
  );
}

Vue-Komponente

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

const props = defineProps(['countryId']);
const emit = defineEmits(['change']);

const states = ref([]);
const loading = ref(false);

watch(() => props.countryId, async (countryId) => {
  if (!countryId) {
    states.value = [];
    return;
  }

  loading.value = true;
  try {
    const response = await fetch(
      `https://api.countrydataapi.com/v1/select/states?apikey=ihr-api-schluessel&country=${countryId}&lang=de`
    );
    const { data } = await response.json();
    states.value = data || [];
  } catch (err) {
    console.error(err);
  } finally {
    loading.value = false;
  }
});
</script>

<template>
  <select @change="emit('change', $event.target.value)" :disabled="!countryId || loading">
    <option value="">{{ loading ? 'Wird geladen...' : 'Bundesland auswaehlen...' }}</option>
    <option v-for="state in states" :key="state.id" :value="state.id">
      {{ state.name }}
    </option>
  </select>
</template>

Laenderspezifische Beispiele

Deutschland (16 Bundeslaender)

const GERMANY_ID = '66c7a6c9e4bda21f4ab10f0d';
const response = await fetch(
  `https://api.countrydataapi.com/v1/select/states?apikey=ihr-api-schluessel&country=${GERMANY_ID}&lang=de`
);
// Gibt zurueck: Baden-Wuerttemberg, Bayern, Berlin, ... Thueringen

Oesterreich (9 Bundeslaender)

const AUSTRIA_ID = '66c7a6c9e4bda21f4ab10ee2';
const response = await fetch(
  `https://api.countrydataapi.com/v1/select/states?apikey=ihr-api-schluessel&country=${AUSTRIA_ID}&lang=de`
);
// Gibt zurueck: Burgenland, Kaernten, ... Wien

Schweiz (26 Kantone)

const SWITZERLAND_ID = '66c7a6c9e4bda21f4ab10fd0';
const response = await fetch(
  `https://api.countrydataapi.com/v1/select/states?apikey=ihr-api-schluessel&country=${SWITZERLAND_ID}&lang=de`
);
// Gibt zurueck: Aargau, Appenzell Ausserrhoden, ... Zuerich

Caching-Strategie

Speichern Sie Bundeslaender nach Land zwischen, um API-Aufrufe zu minimieren:

const stateCache = new Map();

async function getBundeslaender(countryId) {
  // Zuerst Cache pruefen
  if (stateCache.has(countryId)) {
    return stateCache.get(countryId);
  }

  // Von API abrufen
  const response = await fetch(
    `https://api.countrydataapi.com/v1/select/states?apikey=ihr-api-schluessel&country=${countryId}&lang=de`
  );
  const { data } = await response.json();

  // Im Cache speichern
  stateCache.set(countryId, data);

  return data;
}

Fehlerbehandlung

Behandeln Sie Fehler immer elegant:

async function bundeslaenderLaden(countryId) {
  try {
    const response = await fetch(
      `https://api.countrydataapi.com/v1/select/states?apikey=ihr-api-schluessel&country=${countryId}`
    );

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

    const result = await response.json();

    if (!result.success) {
      throw new Error(result.error?.message || 'API-Fehler');
    }

    return result.data;
  } catch (err) {
    console.error('Fehler beim Laden der Bundeslaender:', err);
    // Benutzerfreundliche Fehlermeldung anzeigen
    alert('Fehler beim Laden der Bundeslaender. Bitte erneut versuchen.');
    return [];
  }
}

Performance-Tipps

  1. Lazy Loading: Nur abrufen, wenn ein Land ausgewaehlt wird
  2. Cache nach Land: In Speicher oder localStorage speichern
  3. Debounce bei Anfragen: Wenn Suche/Filter verwendet wird
  4. Ladezustand anzeigen: Visuelles Feedback geben

Rate Limits

  • Kostenloser Plan: 100 Anfragen/Tag
  • Basic Plan: 1.000 Anfragen/Tag
  • Pro Plan: 10.000 Anfragen/Tag
  • Enterprise Plan: Unbegrenzt

Besuchen Sie unsere Preisseite fuer weitere Details.

Haeufige Fehler

Fehlercode Beschreibung Loesung
INVALID_API_KEY API-Schluessel ist ungueltig Pruefen Sie Ihren API-Schluessel im Konto-Dashboard
MISSING_PARAMETER Parameter country fehlt Fuegen Sie die Land-ID in der Anfrage hinzu
INVALID_COUNTRY_ID Land-ID-Format ist ungueltig Verwenden Sie eine gueltige MongoDB ObjectId von /select/countries
QUOTA_EXCEEDED Taegliches Token-Limit erreicht Upgrade auf hoeheren Plan oder warten Sie auf Reset

Siehe die Fehlercode-Dokumentation fuer alle moeglichen Fehler.

Verwandte Endpunkte

Vollstaendige Integrations-Anleitungen

Brauchen Sie Hilfe?


Hinweis: Einige Laender haben keine Verwaltungseinheiten (z.B. Monaco, Vatikanstadt) und geben ein leeres Array zurueck. Behandeln Sie leere Ergebnisse immer elegant in Ihrer Oberflaeche.