L'endpoint /v1/select/states retourne une liste legere de regions/provinces filtrees par pays, avec uniquement les champs id et name, optimisee pour les menus deroulants.
GET https://api.countrydataapi.com/v1/select/states
Incluez votre cle API comme parametre de requete :
?apikey=votre-cle-api
Votre cle API est comme un mot de passe, gardez-la securisee. Obtenez votre cle depuis le tableau de bord de votre compte.
| Parametre | Type | Requis | Description |
|---|---|---|---|
apikey |
string | Oui | Votre cle d'authentification API |
country |
string | Oui | ID du pays (depuis l'endpoint /select/countries) |
lang |
string | Non | Code de langue pour les noms de regions (defaut : en) |
en - Anglais (defaut)es - Espagnolpt - Portugaisfr - Francaisde - Allemandit - Italien# Obtenir les regions de France
curl "https://api.countrydataapi.com/v1/select/states?apikey=votre-cle-api&country=66c7a6c9e4bda21f4ab10f1b&lang=fr"
const API_KEY = 'votre-cle-api';
const COUNTRY_ID = '66c7a6c9e4bda21f4ab10f1b'; // France
async function chargerRegions(countryId) {
const response = await fetch(
`https://api.countrydataapi.com/v1/select/states?apikey=${API_KEY}&country=${countryId}&lang=fr`
);
const data = await response.json();
return data;
}
const regions = await chargerRegions(COUNTRY_ID);
import axios from 'axios';
const response = await axios.get(
'https://api.countrydataapi.com/v1/select/states',
{
params: {
apikey: 'votre-cle-api',
country: '66c7a6c9e4bda21f4ab10f1b',
lang: 'fr',
},
}
);
import requests
response = requests.get(
'https://api.countrydataapi.com/v1/select/states',
params={
'apikey': 'votre-cle-api',
'country': '66c7a6c9e4bda21f4ab10f1b',
'lang': 'fr'
}
)
data = response.json()
<?php
$apiKey = 'votre-cle-api';
$countryId = '66c7a6c9e4bda21f4ab10f1b';
$url = "https://api.countrydataapi.com/v1/select/states?apikey={$apiKey}&country={$countryId}&lang=fr";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$data = json_decode($response, true);
?>
// 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 = 'votre-cle-api';
private readonly BASE_URL = 'https://api.countrydataapi.com/v1';
constructor(private http: HttpClient) {}
getStatesByCountry(countryId: string, lang: string = 'fr'): 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">Chargement des regions...</div>
<div *ngIf="error" class="error">{{ error }}</div>
<select
*ngIf="!loading && !error"
[(ngModel)]="selectedState"
(ngModelChange)="onStateChange($event)"
[disabled]="!countryId"
>
<option value="">Selectionnez une region...</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, 'fr').subscribe({
next: (data) => {
this.states = data;
this.loading = false;
},
error: (err) => {
this.error = 'Echec du chargement des regions';
this.loading = false;
}
});
}
onStateChange(stateId: string) {
this.stateChange.emit(stateId);
}
}
{
"success": true,
"data": [
{
"id": "66c7a6cae4bda21f4ab11d16",
"name": "Auvergne-Rhone-Alpes"
},
{
"id": "66c7a6cae4bda21f4ab11d17",
"name": "Bourgogne-Franche-Comte"
},
{
"id": "66c7a6cae4bda21f4ab11d18",
"name": "Bretagne"
},
{
"id": "66c7a6cae4bda21f4ab11d19",
"name": "Centre-Val de Loire"
},
{
"id": "66c7a6cae4bda21f4ab11d1a",
"name": "Corse"
}
// ... 18 regions au total
]
}
| Champ | Type | Description |
|---|---|---|
success |
boolean | Indique si la requete a reussi |
data |
array | Tableau d'objets region/province |
data[].id |
string | Identifiant unique de la region (MongoDB ObjectId) |
data[].name |
string | Nom de la region/province dans la langue demandee |
{
"success": false,
"error": {
"code": "MISSING_PARAMETER",
"message": "Le parametre requis 'country' est manquant"
}
}
Si un pays n'a pas de regions (ex : petits pays) :
{
"success": true,
"data": []
}
Cet endpoint consomme 1 token par requete.
Astuce : Mettez les donnees de regions en cache par ID de pays pour reduire les appels API lorsque les utilisateurs naviguent d'avant en arriere.
<select id="country" onchange="chargerRegions(this.value)">
<option value="">Selectionnez un pays...</option>
<!-- Rempli depuis /select/countries -->
</select>
<select id="state" disabled>
<option value="">Selectionnez une region...</option>
</select>
<script>
const API_KEY = 'votre-cle-api';
async function chargerRegions(countryId) {
const stateSelect = document.getElementById('state');
// Reinitialiser et desactiver
stateSelect.innerHTML = '<option value="">Chargement...</option>';
stateSelect.disabled = true;
if (!countryId) {
stateSelect.innerHTML = '<option value="">Selectionnez une region...</option>';
return;
}
try {
const response = await fetch(
`https://api.countrydataapi.com/v1/select/states?apikey=${API_KEY}&country=${countryId}&lang=fr`
);
const { success, data, error } = await response.json();
if (!success) {
console.error('Erreur API:', error);
stateSelect.innerHTML = '<option value="">Erreur de chargement des regions</option>';
return;
}
stateSelect.innerHTML = '<option value="">Selectionnez une region...</option>';
data.forEach(state => {
stateSelect.add(new Option(state.name, state.id));
});
stateSelect.disabled = false;
} catch (err) {
console.error('Erreur Reseau:', err);
stateSelect.innerHTML = '<option value="">Erreur de chargement des regions</option>';
}
}
</script>
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=votre-cle-api&country=${countryId}&lang=fr`
)
.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 ? 'Chargement...' : 'Selectionnez une region...'}
</option>
{states.map(state => (
<option key={state.id} value={state.id}>
{state.name}
</option>
))}
</select>
);
}
<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=votre-cle-api&country=${countryId}&lang=fr`
);
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 ? 'Chargement...' : 'Selectionnez une region...' }}</option>
<option v-for="state in states" :key="state.id" :value="state.id">
{{ state.name }}
</option>
</select>
</template>
const FRANCE_ID = '66c7a6c9e4bda21f4ab10f1b';
const response = await fetch(
`https://api.countrydataapi.com/v1/select/states?apikey=votre-cle-api&country=${FRANCE_ID}&lang=fr`
);
// Retourne : Auvergne-Rhone-Alpes, Bretagne, ... Occitanie
const CANADA_ID = '66c7a6c9e4bda21f4ab10ef7';
const response = await fetch(
`https://api.countrydataapi.com/v1/select/states?apikey=votre-cle-api&country=${CANADA_ID}&lang=fr`
);
// Retourne : Alberta, Colombie-Britannique, ... Yukon
const BELGIUM_ID = '66c7a6c9e4bda21f4ab10ee9';
const response = await fetch(
`https://api.countrydataapi.com/v1/select/states?apikey=votre-cle-api&country=${BELGIUM_ID}&lang=fr`
);
// Retourne : Anvers, Brabant flamand, ... Luxembourg
Mettez les regions en cache par pays pour minimiser les appels API :
const stateCache = new Map();
async function getRegions(countryId) {
// Verifier le cache d'abord
if (stateCache.has(countryId)) {
return stateCache.get(countryId);
}
// Recuperer depuis l'API
const response = await fetch(
`https://api.countrydataapi.com/v1/select/states?apikey=votre-cle-api&country=${countryId}&lang=fr`
);
const { data } = await response.json();
// Sauvegarder en cache
stateCache.set(countryId, data);
return data;
}
Gerez toujours les erreurs avec elegance :
async function chargerRegions(countryId) {
try {
const response = await fetch(
`https://api.countrydataapi.com/v1/select/states?apikey=votre-cle-api&country=${countryId}`
);
if (!response.ok) {
throw new Error(`Erreur HTTP! statut: ${response.status}`);
}
const result = await response.json();
if (!result.success) {
throw new Error(result.error?.message || 'Erreur API');
}
return result.data;
} catch (err) {
console.error('Echec du chargement des regions:', err);
// Afficher un message convivial a l'utilisateur
alert('Echec du chargement des regions. Veuillez reessayer.');
return [];
}
}
Consultez notre page de tarifs pour plus de details.
| Code d'Erreur | Description | Solution |
|---|---|---|
INVALID_API_KEY |
Cle API invalide | Verifiez votre cle API dans le tableau de bord du compte |
MISSING_PARAMETER |
Parametre country manquant |
Incluez l'ID du pays dans la requete |
INVALID_COUNTRY_ID |
Format de l'ID du pays invalide | Utilisez un MongoDB ObjectId valide depuis /select/countries |
QUOTA_EXCEEDED |
Limite quotidienne de tokens atteinte | Mettez a niveau le forfait ou attendez la reinitialisation |
Consultez la documentation des Codes d'Erreur pour toutes les erreurs possibles.
Note : Certains pays n'ont pas de divisions administratives (ex : Monaco, Cite du Vatican) et retourneront un tableau vide. Gerez toujours les resultats vides avec elegance dans votre interface.