Exemples de code
Exemples d'intégration en JavaScript, Python et cURL.
JavaScript / Node.js
Recherche simple
search.js
const API_KEY = process.env.BCE_API_KEY;
const BASE_URL = 'https://companybelgium.be/api';
async function searchCompanies(name, options = {}) {
const params = new URLSearchParams({ name, ...options });
const response = await fetch(`${BASE_URL}/companies/search?${params}`, {
headers: { 'X-API-Key': API_KEY },
});
if (!response.ok) {
throw new Error(`API error: ${response.status}`);
}
return response.json();
}
// Usage
const result = await searchCompanies('Proximus', { zipCode: '1000' });
console.log(result.data.results);Classe client API complète
bce-kbo-client.js
class BceKboClient {
constructor(apiKey, apiSecret) {
this.baseUrl = 'https://companybelgium.be/api';
this.headers = {
'X-API-Key': apiKey,
...(apiSecret && { 'X-API-Secret': apiSecret }),
};
}
async #request(endpoint, params = {}) {
const url = new URL(`${this.baseUrl}${endpoint}`);
Object.entries(params).forEach(([key, value]) => {
if (value !== undefined) url.searchParams.set(key, String(value));
});
const response = await fetch(url, { headers: this.headers });
const data = await response.json();
if (!data.success) {
throw new Error(data.error || `HTTP ${response.status}`);
}
return data;
}
async searchByName(name, options = {}) {
return this.#request('/companies/search', { name, ...options });
}
async searchByAddress(postalCode, street, houseNumber) {
return this.#request('/companies/address', { postalCode, street, houseNumber });
}
async getCompany(id) {
return this.#request(`/companies/${id}`);
}
async checkPeppol(vatNumber) {
return this.#request('/peppol/check', { vatNumber });
}
async health() {
return this.#request('/health');
}
}
// Usage
const client = new BceKboClient('pk_live_...', 'sk_live_...');
const company = await client.getCompany('0202.239.951');
console.log(company.data.name); // "Proximus SA de droit public"Python
Recherche simple
search.py
import os
import requests
API_KEY = os.environ['BCE_API_KEY']
BASE_URL = 'https://companybelgium.be/api'
def search_companies(name, **kwargs):
"""Rechercher des entreprises belges par nom."""
response = requests.get(
f'{BASE_URL}/companies/search',
params={'name': name, **kwargs},
headers={'X-API-Key': API_KEY}
)
response.raise_for_status()
return response.json()
# Usage
result = search_companies('Proximus', zipCode='1000')
for company in result['data']['results']:
print(f"{company['name']} ({company['enterpriseNumber']})")Classe client API complète
bce_kbo_client.py
import requests
from typing import Optional
class BceKboClient:
"""Client Python pour l'API BCE/KBO."""
def __init__(self, api_key: str, api_secret: Optional[str] = None):
self.base_url = 'https://companybelgium.be/api'
self.session = requests.Session()
self.session.headers.update({'X-API-Key': api_key})
if api_secret:
self.session.headers.update({'X-API-Secret': api_secret})
def _request(self, endpoint: str, params: dict = None):
response = self.session.get(f'{self.base_url}{endpoint}', params=params)
data = response.json()
if not data.get('success'):
raise Exception(data.get('error', f'HTTP {response.status_code}'))
return data
def search_by_name(self, name: str, **kwargs):
return self._request('/companies/search', {'name': name, **kwargs})
def search_by_address(self, postal_code: str, street: str, house_number: str = None):
params = {'postalCode': postal_code, 'street': street}
if house_number:
params['houseNumber'] = house_number
return self._request('/companies/address', params)
def get_company(self, enterprise_number: str):
return self._request(f'/companies/{enterprise_number}')
def check_peppol(self, vat_number: str):
return self._request('/peppol/check', {'vatNumber': vat_number})
def health(self):
return self._request('/health')
# Usage
client = BceKboClient('pk_live_...', 'sk_live_...')
company = client.get_company('0202.239.951')
print(company['data']['name']) # "Proximus SA de droit public"cURL
Recherche d'entreprises
Exemples cURL
# Recherche par nom curl -s "https://companybelgium.be/api/companies/search?name=Proximus" \ -H "X-API-Key: pk_live_votre_cle" | jq . # Recherche par adresse curl -s "https://companybelgium.be/api/companies/address?postalCode=1080&street=RUE+DE+LA+COLONNE" \ -H "X-API-Key: pk_live_votre_cle" | jq . # Détails d'une entreprise curl -s "https://companybelgium.be/api/companies/0202.239.951" \ -H "X-API-Key: pk_live_votre_cle" | jq . # Vérification Peppol curl -s "https://companybelgium.be/api/peppol/check?vatNumber=1033022383" \ -H "X-API-Key: pk_live_votre_cle" | jq . # Santé de l'API curl -s "https://companybelgium.be/api/health" | jq .
Script Bash complet
test-api.sh
#!/bin/bash
# Script de test de l'API BCE/KBO
API_KEY="pk_live_votre_cle"
BASE_URL="https://companybelgium.be/api"
echo "=== Test Health ==="
curl -s "$BASE_URL/health" | jq '.status'
echo -e "\n=== Recherche: Proximus ==="
curl -s "$BASE_URL/companies/search?name=Proximus" \
-H "X-API-Key: $API_KEY" | jq '.data.results[] | {name, enterpriseNumber}'
echo -e "\n=== Détails: 0202.239.951 ==="
curl -s "$BASE_URL/companies/0202.239.951" \
-H "X-API-Key: $API_KEY" | jq '{name: .data.name, status: .data.status, address: .data.address}'
echo -e "\n=== Peppol Check ==="
curl -s "$BASE_URL/peppol/check?vatNumber=1033022383" \
-H "X-API-Key: $API_KEY" | jq '{registered: .data.isRegistered, entity: .data.entityName}'PHP
search.php
<?php
$apiKey = getenv('BCE_API_KEY');
$baseUrl = 'https://companybelgium.be/api';
function searchCompanies(string $name, array $options = []): array {
global $apiKey, $baseUrl;
$params = http_build_query(array_merge(['name' => $name], $options));
$context = stream_context_create([
'http' => [
'header' => "X-API-Key: $apiKey\r\n",
],
]);
$response = file_get_contents("$baseUrl/companies/search?$params", false, $context);
return json_decode($response, true);
}
// Usage
$result = searchCompanies('Proximus', ['zipCode' => '1000']);
foreach ($result['data']['results'] as $company) {
echo "{$company['name']} - {$company['enterpriseNumber']}\n";
}