Exemples de code
Exemples pratiques d'utilisation de l'API v2 en cURL, JavaScript et Python. Tous les exemples utilisent la base URL https://companybelgium.be/api/v2.
1. Rechercher une entreprise par nom
Utilisez l'endpoint GET /api/v2/denominations pour rechercher des entreprises par leur denomination.
# Recherche par denomination
curl -H "X-API-Key: ${API_KEY}" -H "X-API-Secret: ${API_SECRET}" \
"https://companybelgium.be/api/v2/denominations?q=Proximus&limit=5"const API_KEY = process.env.API_KEY;
const API_SECRET = process.env.API_SECRET;
const BASE_URL = 'https://companybelgium.be/api/v2';
async function searchByName(query, limit = 5) {
const params = new URLSearchParams({ q: query, limit: String(limit) });
const response = await fetch(`${BASE_URL}/denominations?${params}`, {
headers: {
'X-API-Key': API_KEY,
'X-API-Secret': API_SECRET,
},
});
const data = await response.json();
if (!data.success) {
throw new Error(data.error);
}
return data.data;
}
// Usage
const results = await searchByName('Proximus');
console.log(results);import os
import requests
API_KEY = os.environ['API_KEY']
API_SECRET = os.environ['API_SECRET']
BASE_URL = 'https://companybelgium.be/api/v2'
def search_by_name(query: str, limit: int = 5) -> dict:
"""Rechercher des entreprises par denomination."""
response = requests.get(
f'{BASE_URL}/denominations',
params={'q': query, 'limit': limit},
headers={
'X-API-Key': API_KEY,
'X-API-Secret': API_SECRET,
},
)
response.raise_for_status()
data = response.json()
if not data['success']:
raise Exception(data.get('error', 'Unknown error'))
return data['data']
# Usage
results = search_by_name('Proximus')
for item in results:
print(f"{item['denomination']} — {item['enterpriseNumber']}")2. Obtenir le profil complet d'une entreprise
L'endpoint GET /api/v2/enterprise/{num} retourne toutes les informations d'une entreprise : denominations, adresses, activites, contacts, etc.
# Profil complet
curl -H "X-API-Key: ${API_KEY}" -H "X-API-Secret: ${API_SECRET}" \
https://companybelgium.be/api/v2/enterprise/1033022383
# Uniquement les activites
curl -H "X-API-Key: ${API_KEY}" -H "X-API-Secret: ${API_SECRET}" \
https://companybelgium.be/api/v2/enterprise/1033022383/activities
# Uniquement l'adresse
curl -H "X-API-Key: ${API_KEY}" -H "X-API-Secret: ${API_SECRET}" \
https://companybelgium.be/api/v2/enterprise/1033022383/addressasync function getEnterpriseProfile(enterpriseNumber) {
const response = await fetch(
`${BASE_URL}/enterprise/${enterpriseNumber}`,
{
headers: {
'X-API-Key': API_KEY,
'X-API-Secret': API_SECRET,
},
}
);
const data = await response.json();
if (!data.success) {
if (response.status === 404) {
console.log('Entreprise introuvable');
return null;
}
throw new Error(data.error);
}
return data.data;
}
// Usage
const enterprise = await getEnterpriseProfile('1033022383');
console.log(enterprise.denominations);
console.log(enterprise.addresses);
console.log(enterprise.activities);def get_enterprise_profile(enterprise_number: str) -> dict | None:
"""Recuperer le profil complet d'une entreprise."""
response = requests.get(
f'{BASE_URL}/enterprise/{enterprise_number}',
headers={
'X-API-Key': API_KEY,
'X-API-Secret': API_SECRET,
},
)
if response.status_code == 404:
print('Entreprise introuvable')
return None
response.raise_for_status()
data = response.json()
if not data['success']:
raise Exception(data.get('error', 'Unknown error'))
return data['data']
# Usage
enterprise = get_enterprise_profile('1033022383')
if enterprise:
print(f"Nom: {enterprise['denominations'][0]['denomination']}")
print(f"Statut: {enterprise['status']}")3. Valider un numero TVA
L'endpoint GET /api/v2/vat/{vatNumber} interroge le service VIES de la Commission europeenne pour verifier la validite d'un numero TVA intracommunautaire.
# TVA belge
curl -H "X-API-Key: ${API_KEY}" -H "X-API-Secret: ${API_SECRET}" \
https://companybelgium.be/api/v2/vat/BE1033022383
# TVA francaise
curl -H "X-API-Key: ${API_KEY}" -H "X-API-Secret: ${API_SECRET}" \
https://companybelgium.be/api/v2/vat/FR12345678901
# TVA allemande
curl -H "X-API-Key: ${API_KEY}" -H "X-API-Secret: ${API_SECRET}" \
https://companybelgium.be/api/v2/vat/DE123456789async function checkVat(vatNumber) {
const response = await fetch(
`${BASE_URL}/vat/${vatNumber}`,
{
headers: {
'X-API-Key': API_KEY,
'X-API-Secret': API_SECRET,
},
}
);
const data = await response.json();
if (!data.success) {
throw new Error(data.error);
}
const vat = data.data;
console.log(`TVA ${vatNumber}: ${vat.valid ? 'VALIDE' : 'INVALIDE'}`);
if (vat.valid) {
console.log(` Nom: ${vat.name}`);
console.log(` Adresse: ${vat.address}`);
}
return vat;
}
// Usage
await checkVat('BE1033022383');def check_vat(vat_number: str) -> dict:
"""Valider un numero TVA via VIES."""
response = requests.get(
f'{BASE_URL}/vat/{vat_number}',
headers={
'X-API-Key': API_KEY,
'X-API-Secret': API_SECRET,
},
)
response.raise_for_status()
data = response.json()
if not data['success']:
raise Exception(data.get('error', 'Unknown error'))
vat = data['data']
status = 'VALIDE' if vat['valid'] else 'INVALIDE'
print(f"TVA {vat_number}: {status}")
if vat['valid']:
print(f" Nom: {vat['name']}")
print(f" Adresse: {vat['address']}")
return vat
# Usage
check_vat('BE1033022383')4. Surveiller son quota d'utilisation
L'endpoint GET /api/v2/me retourne les informations de votre compte, votre plan actuel et votre consommation mensuelle.
curl -H "X-API-Key: ${API_KEY}" -H "X-API-Secret: ${API_SECRET}" \
https://companybelgium.be/api/v2/measync function checkUsage() {
const response = await fetch(`${BASE_URL}/me`, {
headers: {
'X-API-Key': API_KEY,
'X-API-Secret': API_SECRET,
},
});
const data = await response.json();
if (!data.success) {
throw new Error(data.error);
}
const { plan, usage } = data.data;
const used = usage.currentMonth.requests;
const limit = plan.requestsPerMonth;
const pct = Math.round((used / limit) * 100);
console.log(`Plan: ${plan.name}`);
console.log(`Utilisation: ${used} / ${limit} (${pct}%)`);
console.log(`Limite horaire: ${plan.requestsPerHour} req/h`);
if (pct > 80) {
console.warn('Attention: plus de 80% du quota mensuel consomme !');
}
return data.data;
}
// Usage
await checkUsage();def check_usage() -> dict:
"""Verifier l'utilisation du quota API."""
response = requests.get(
f'{BASE_URL}/me',
headers={
'X-API-Key': API_KEY,
'X-API-Secret': API_SECRET,
},
)
response.raise_for_status()
data = response.json()
if not data['success']:
raise Exception(data.get('error', 'Unknown error'))
plan = data['data']['plan']
usage = data['data']['usage']['currentMonth']
used = usage['requests']
limit = plan['requestsPerMonth']
pct = round((used / limit) * 100)
print(f"Plan: {plan['name']}")
print(f"Utilisation: {used} / {limit} ({pct}%)")
print(f"Limite horaire: {plan['requestsPerHour']} req/h")
if pct > 80:
print("Attention: plus de 80% du quota mensuel consomme !")
return data['data']
# Usage
check_usage()5. Configurer un webhook pour les changements
Creez un webhook pour recevoir des notifications en temps reel lorsque les donnees d'une entreprise sont mises a jour dans la base BCE/KBO.
# Creer un webhook
curl -X POST https://companybelgium.be/api/v2/webhook \
-H "X-API-Key: ${API_KEY}" \
-H "X-API-Secret: ${API_SECRET}" \
-H "Content-Type: application/json" \
-d '{
"name": "Mon webhook de production",
"url": "https://mon-app.example.com/webhooks/bce",
"entityNumbers": ["1033022383", "0202239951"]
}'
# Ajouter des entreprises a surveiller
curl -X POST https://companybelgium.be/api/v2/webhook/${WEBHOOK_ID}/subscriptions \
-H "X-API-Key: ${API_KEY}" \
-H "X-API-Secret: ${API_SECRET}" \
-H "Content-Type: application/json" \
-d '{
"entityNumbers": ["0417497106"]
}'
# Tester le webhook
curl -X POST https://companybelgium.be/api/v2/webhook/${WEBHOOK_ID}/trigger \
-H "X-API-Key: ${API_KEY}" \
-H "X-API-Secret: ${API_SECRET}" \
-H "Content-Type: application/json" \
-d '{
"entityNumber": "1033022383",
"data": {"note": "Test manuel"}
}'async function setupWebhook(name, callbackUrl, entityNumbers) {
// 1. Creer le webhook
const createResponse = await fetch(`${BASE_URL}/webhook`, {
method: 'POST',
headers: {
'X-API-Key': API_KEY,
'X-API-Secret': API_SECRET,
'Content-Type': 'application/json',
},
body: JSON.stringify({
name,
url: callbackUrl,
entityNumbers,
}),
});
const createData = await createResponse.json();
if (!createData.success) {
throw new Error(createData.error);
}
const webhook = createData.data;
console.log(`Webhook cree: ${webhook.id}`);
console.log(`HMAC Secret: ${webhook.hmacSecret}`);
console.log('Conservez ce secret pour verifier les signatures !');
return webhook;
}
// 2. Recepteur de webhook (Express.js)
import crypto from 'crypto';
function verifyWebhookSignature(payload, signature, secret) {
const expected = crypto
.createHmac('sha256', secret)
.update(payload)
.digest('hex');
return crypto.timingSafeEqual(
Buffer.from(signature),
Buffer.from(expected)
);
}
// Route Express
app.post('/webhooks/bce', (req, res) => {
const signature = req.headers['x-webhook-signature'];
const payload = JSON.stringify(req.body);
if (!verifyWebhookSignature(payload, signature, HMAC_SECRET)) {
return res.status(401).json({ error: 'Invalid signature' });
}
console.log('Evenement recu:', req.body.event);
console.log('Entreprise:', req.body.entityNumber);
res.status(200).json({ received: true });
});import hmac
import hashlib
from flask import Flask, request, jsonify
def setup_webhook(name: str, callback_url: str, entity_numbers: list) -> dict:
"""Creer un webhook pour surveiller des entreprises."""
response = requests.post(
f'{BASE_URL}/webhook',
headers={
'X-API-Key': API_KEY,
'X-API-Secret': API_SECRET,
'Content-Type': 'application/json',
},
json={
'name': name,
'url': callback_url,
'entityNumbers': entity_numbers,
},
)
response.raise_for_status()
data = response.json()
if not data['success']:
raise Exception(data.get('error', 'Unknown error'))
webhook = data['data']
print(f"Webhook cree: {webhook['id']}")
print(f"HMAC Secret: {webhook['hmacSecret']}")
return webhook
# Recepteur de webhook (Flask)
app = Flask(__name__)
HMAC_SECRET = 'whsec_...'
def verify_signature(payload: bytes, signature: str) -> bool:
expected = hmac.new(
HMAC_SECRET.encode(),
payload,
hashlib.sha256
).hexdigest()
return hmac.compare_digest(expected, signature)
@app.route('/webhooks/bce', methods=['POST'])
def handle_webhook():
signature = request.headers.get('X-Webhook-Signature', '')
if not verify_signature(request.data, signature):
return jsonify(error='Invalid signature'), 401
event = request.json
print(f"Evenement: {event['event']}")
print(f"Entreprise: {event['entityNumber']}")
return jsonify(received=True), 200
# Usage
setup_webhook(
name='Production',
callback_url='https://mon-app.example.com/webhooks/bce',
entity_numbers=['1033022383', '0202239951'],
)Client API complet
Exemple de classe client reutilisable qui encapsule tous les appels API v2 avec gestion des erreurs et retry automatique.
class CompanyBelgiumV2 {
constructor(apiKey, apiSecret) {
this.baseUrl = 'https://companybelgium.be/api/v2';
this.headers = {
'X-API-Key': apiKey,
'X-API-Secret': apiSecret,
'Content-Type': 'application/json',
};
}
async #request(method, endpoint, { params, body } = {}) {
const url = new URL(`${this.baseUrl}${endpoint}`);
if (params) {
Object.entries(params).forEach(([k, v]) => {
if (v !== undefined) url.searchParams.set(k, String(v));
});
}
const response = await fetch(url, {
method,
headers: this.headers,
body: body ? JSON.stringify(body) : undefined,
});
const data = await response.json();
if (!data.success) {
const err = new Error(data.error || `HTTP ${response.status}`);
err.status = response.status;
err.rateLimitReset = response.headers.get('X-RateLimit-Reset');
throw err;
}
return data;
}
// Entreprise
getEnterprise(num) { return this.#request('GET', `/enterprise/${num}`); }
getActivities(num) { return this.#request('GET', `/enterprise/${num}/activities`); }
getAddress(num) { return this.#request('GET', `/enterprise/${num}/address`); }
getContact(num) { return this.#request('GET', `/enterprise/${num}/contact`); }
getDenominations(num) { return this.#request('GET', `/enterprise/${num}/denominations`); }
getRoles(num) { return this.#request('GET', `/enterprise/${num}/roles`); }
getFinancial(num, years) { return this.#request('GET', `/enterprise/${num}/financial`, { params: years ? { years } : {} }); }
getFinancialIntelligence(num, years) { return this.#request('GET', `/enterprise/${num}/financial/intelligence`, { params: years ? { years } : {} }); }
getPaymentRisk(num) { return this.#request('GET', `/enterprise/${num}/payment-risk`); }
getEstablishments(num) { return this.#request('GET', `/enterprise/${num}/establishments`); }
// Etablissement
getEstablishment(num) { return this.#request('GET', `/establishment/${num}`); }
// Recherche
searchDenominations(q, opts){ return this.#request('GET', '/denominations', { params: { q, ...opts } }); }
searchNaces(q) { return this.#request('GET', '/naces', { params: { q } }); }
getJuridicalForms() { return this.#request('GET', '/juridical-forms'); }
// TVA
checkVat(vatNumber) { return this.#request('GET', `/vat/${vatNumber}`); }
// Compte
getMe() { return this.#request('GET', '/me'); }
// Webhooks
createWebhook(data) { return this.#request('POST', '/webhook', { body: data }); }
getWebhook(id) { return this.#request('GET', `/webhook/${id}`); }
deleteWebhook(id) { return this.#request('DELETE', `/webhook/${id}`); }
}
// Usage
const api = new CompanyBelgiumV2('pk_live_...', 'sk_live_...');
const enterprise = await api.getEnterprise('1033022383');
console.log(enterprise.data);
const vat = await api.checkVat('BE1033022383');
console.log(vat.data.valid);
const me = await api.getMe();
console.log(me.data.usage);import requests
from typing import Optional
class CompanyBelgiumV2:
"""Client Python pour l'API Company Belgium v2."""
def __init__(self, api_key: str, api_secret: str):
self.base_url = 'https://companybelgium.be/api/v2'
self.session = requests.Session()
self.session.headers.update({
'X-API-Key': api_key,
'X-API-Secret': api_secret,
'Content-Type': 'application/json',
})
def _request(self, method: str, endpoint: str,
params: dict = None, json: dict = None) -> dict:
response = self.session.request(
method,
f'{self.base_url}{endpoint}',
params=params,
json=json,
)
data = response.json()
if not data.get('success'):
raise Exception(data.get('error', f'HTTP {response.status_code}'))
return data
# Entreprise
def get_enterprise(self, num: str):
return self._request('GET', f'/enterprise/{num}')
def get_activities(self, num: str):
return self._request('GET', f'/enterprise/{num}/activities')
def get_address(self, num: str):
return self._request('GET', f'/enterprise/{num}/address')
def get_contact(self, num: str):
return self._request('GET', f'/enterprise/{num}/contact')
def get_denominations(self, num: str):
return self._request('GET', f'/enterprise/{num}/denominations')
def get_roles(self, num: str):
return self._request('GET', f'/enterprise/{num}/roles')
# Recherche
def search_denominations(self, q: str, **kwargs):
return self._request('GET', '/denominations', params={'q': q, **kwargs})
# TVA
def check_vat(self, vat_number: str):
return self._request('GET', f'/vat/{vat_number}')
# Compte
def get_me(self):
return self._request('GET', '/me')
# Webhooks
def create_webhook(self, name: str, url: str, entity_numbers: list):
return self._request('POST', '/webhook', json={
'name': name, 'url': url, 'entityNumbers': entity_numbers,
})
def delete_webhook(self, webhook_id: str):
return self._request('DELETE', f'/webhook/{webhook_id}')
# Usage
api = CompanyBelgiumV2('pk_live_...', 'sk_live_...')
enterprise = api.get_enterprise('1033022383')
print(enterprise['data'])
vat = api.check_vat('BE1033022383')
print(f"Valide: {vat['data']['valid']}")
me = api.get_me()
print(f"Requetes ce mois: {me['data']['usage']['currentMonth']['requests']}")