Esempi di utilizzo delle API
Questa pagina contiene esempi di implementazione per le principali operazioni sulle API di Formedil BC in diversi linguaggi di programmazione.
Verifica di un certificato
Questi esempi mostrano come verificare l'autenticità di un certificato utilizzando l'API /api/verify/:code.
cURL
| curl -X GET \
'https://bc.formedil.it/api/verify/7a89f023cbd4e7a59378ceba27f8654a12f8b987-libretto-5d41402abc4b2a76b9719d911017c592' \
-H 'Authorization: Bearer YOUR_API_TOKEN' \
-H 'Content-Type: application/json'
|
JavaScript (Browser)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28 | const apiToken = 'YOUR_API_TOKEN';
const certificateCode = '7a89f023cbd4e7a59378ceba27f8654a12f8b987-libretto-5d41402abc4b2a76b9719d911017c592';
async function verificaCertificato() {
try {
const response = await fetch(`https://bc.formedil.it/api/verify/${certificateCode}`, {
method: 'GET',
headers: {
'Authorization': `Bearer ${apiToken}`,
'Content-Type': 'application/json'
}
});
const data = await response.json();
if (data.result && data.result.verifyStatus === 'certified') {
console.log('Il certificato è valido e autentico!');
} else if (data.result && data.result.verifyStatus === 'different') {
console.log('Il certificato è stato alterato!');
} else if (data.error) {
console.error('Errore:', data.error.message);
}
return data;
} catch (error) {
console.error('Errore di rete:', error);
}
}
|
Node.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32 | const fetch = require('node-fetch');
const apiToken = 'YOUR_API_TOKEN';
const certificateCode = '7a89f023cbd4e7a59378ceba27f8654a12f8b987-libretto-5d41402abc4b2a76b9719d911017c592';
async function verificaCertificato() {
try {
const response = await fetch(`https://bc.formedil.it/api/verify/${certificateCode}`, {
method: 'GET',
headers: {
'Authorization': `Bearer ${apiToken}`,
'Content-Type': 'application/json'
}
});
const data = await response.json();
if (data.result && data.result.verifyStatus === 'certified') {
console.log('Il certificato è valido e autentico!');
} else if (data.result && data.result.verifyStatus === 'different') {
console.log('Il certificato è stato alterato!');
} else if (data.error) {
console.error('Errore:', data.error.message);
}
return data;
} catch (error) {
console.error('Errore di rete:', error);
}
}
verificaCertificato();
|
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32 | import requests
api_token = 'YOUR_API_TOKEN'
certificate_code = '7a89f023cbd4e7a59378ceba27f8654a12f8b987-libretto-5d41402abc4b2a76b9719d911017c592'
def verifica_certificato():
headers = {
'Authorization': f'Bearer {api_token}',
'Content-Type': 'application/json'
}
url = f'https://api.formedilbc.it/api/verify/{certificate_code}'
try:
response = requests.get(url, headers=headers)
data = response.json()
if response.status_code == 200:
if data['result'] and data['result']['verifyStatus'] == 'certified':
print('Il certificato è valido e autentico!')
elif data['result'] and data['result']['verifyStatus'] == 'different':
print('Il certificato è stato alterato!')
elif data['error']:
print(f'Errore: {data["error"]["message"]}')
else:
print(f'Errore HTTP: {response.status_code}')
return data
except Exception as e:
print(f'Errore di rete: {str(e)}')
verifica_certificato()
|
PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47 | <?php
$apiToken = 'YOUR_API_TOKEN';
$certificateCode = '7a89f023cbd4e7a59378ceba27f8654a12f8b987-libretto-5d41402abc4b2a76b9719d911017c592';
function verificaCertificato($apiToken, $certificateCode) {
$url = "https://bc.formedil.it/api/verify/" . $certificateCode;
$headers = [
'Authorization: Bearer ' . $apiToken,
'Content-Type: application/json'
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (curl_errno($ch)) {
echo 'Errore cURL: ' . curl_error($ch);
return null;
}
curl_close($ch);
$data = json_decode($response, true);
if ($httpCode == 200) {
if (isset($data['result']) && $data['result']['verifyStatus'] == 'certified') {
echo "Il certificato è valido e autentico!\n";
} elseif (isset($data['result']) && $data['result']['verifyStatus'] == 'different') {
echo "Il certificato è stato alterato!\n";
} elseif (isset($data['error'])) {
echo "Errore: " . $data['error']['message'] . "\n";
}
} else {
echo "Errore HTTP: " . $httpCode . "\n";
}
return $data;
}
$result = verificaCertificato($apiToken, $certificateCode);
print_r($result);
|
Ricerca persone
Questi esempi mostrano come utilizzare l'API di ricerca persone /api/ricerca-persone/.
cURL
| # Ricerca standard
curl -X GET \
'https://bc.formedil.it/api/ricerca-persone/?q=Rossi' \
-H 'Authorization: Bearer YOUR_API_TOKEN' \
-H 'Content-Type: application/json'
# Ricerca solo formatori
curl -X GET \
'https://bc.formedil.it/api/ricerca-persone/?q=Rossi&formatore=true' \
-H 'Authorization: Bearer YOUR_API_TOKEN' \
-H 'Content-Type: application/json'
|
JavaScript (Browser)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36 | const apiToken = 'YOUR_API_TOKEN';
async function ricercaPersone(searchTerm, soloFormatori = false) {
try {
const url = new URL('https://bc.formedil.it/api/ricerca-persone/');
url.searchParams.append('q', searchTerm);
if (soloFormatori) {
url.searchParams.append('formatore', 'true');
}
const response = await fetch(url, {
method: 'GET',
headers: {
'Authorization': `Bearer ${apiToken}`,
'Content-Type': 'application/json'
}
});
const data = await response.json();
if (data.error) {
console.error('Errore:', data.error.message);
return;
}
console.log(`Trovate ${data.result ? data.result.length : 0} persone`);
return data;
} catch (error) {
console.error('Errore di rete:', error);
}
}
// Esempio di utilizzo
ricercaPersone('Rossi');
ricercaPersone('Bianchi', true); // Solo formatori
|
Node.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37 | const fetch = require('node-fetch');
const apiToken = 'YOUR_API_TOKEN';
async function ricercaPersone(searchTerm, soloFormatori = false) {
try {
let url = `https://bc.formedil.it/api/ricerca-persone/?q=${encodeURIComponent(searchTerm)}`;
if (soloFormatori) {
url += '&formatore=true';
}
const response = await fetch(url, {
method: 'GET',
headers: {
'Authorization': `Bearer ${apiToken}`,
'Content-Type': 'application/json'
}
});
const data = await response.json();
if (data.error) {
console.error('Errore:', data.error.message);
return;
}
console.log(`Trovate ${data.result ? data.result.length : 0} persone`);
return data;
} catch (error) {
console.error('Errore di rete:', error);
}
}
// Esempio di utilizzo
ricercaPersone('Rossi');
ricercaPersone('Bianchi', true); // Solo formatori
|
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38 | import requests
api_token = 'YOUR_API_TOKEN'
def ricerca_persone(search_term, solo_formatori=False):
headers = {
'Authorization': f'Bearer {api_token}',
'Content-Type': 'application/json'
}
params = {
'q': search_term
}
if solo_formatori:
params['formatore'] = 'true'
url = 'https://bc.formedil.it/api/ricerca-persone/'
try:
response = requests.get(url, headers=headers, params=params)
data = response.json()
if response.status_code == 200:
if data.get('error'):
print(f'Errore: {data["error"]["message"]}')
else:
print(f'Trovate {len(data["result"]) if data["result"] else 0} persone')
else:
print(f'Errore HTTP: {response.status_code}')
return data
except Exception as e:
print(f'Errore di rete: {str(e)}')
# Esempio di utilizzo
ricerca_persone('Rossi')
ricerca_persone('Bianchi', True) # Solo formatori
|
PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50 | <?php
$apiToken = 'YOUR_API_TOKEN';
function ricercaPersone($apiToken, $searchTerm, $soloFormatori = false) {
$url = "https://bc.formedil.it/api/ricerca-persone/?q=" . urlencode($searchTerm);
if ($soloFormatori) {
$url .= "&formatore=true";
}
$headers = [
'Authorization: Bearer ' . $apiToken,
'Content-Type: application/json'
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (curl_errno($ch)) {
echo 'Errore cURL: ' . curl_error($ch);
return null;
}
curl_close($ch);
$data = json_decode($response, true);
if ($httpCode == 200) {
if (isset($data['error'])) {
echo "Errore: " . $data['error']['message'] . "\n";
} else {
$numResults = isset($data['result']) ? count($data['result']) : 0;
echo "Trovate " . $numResults . " persone\n";
}
} else {
echo "Errore HTTP: " . $httpCode . "\n";
}
return $data;
}
// Esempio di utilizzo
$result1 = ricercaPersone($apiToken, 'Rossi');
$result2 = ricercaPersone($apiToken, 'Bianchi', true); // Solo formatori
|
Gestione degli errori
Quando si utilizzano le API, è importante gestire correttamente gli errori. Ecco un esempio di gestione degli errori comuni:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52 | async function callApi(endpoint, params = {}) {
try {
const url = new URL(`https://bc.formedil.it/api/${endpoint}`);
// Aggiungi parametri query
Object.keys(params).forEach(key => {
url.searchParams.append(key, params[key]);
});
const response = await fetch(url, {
method: 'GET',
headers: {
'Authorization': `Bearer ${apiToken}`,
'Content-Type': 'application/json'
}
});
// Gestione errori HTTP
if (!response.ok) {
switch (response.status) {
case 400:
throw new Error('Richiesta non valida. Controllare i parametri.');
case 401:
throw new Error('Autenticazione fallita. Controllare il token API.');
case 403:
throw new Error('Accesso negato. Token senza permessi sufficienti.');
case 404:
throw new Error('Risorsa non trovata.');
case 429:
throw new Error('Troppe richieste. Attendere prima di riprovare.');
case 500:
case 502:
case 503:
throw new Error('Errore del server. Riprovare più tardi.');
default:
throw new Error(`Errore HTTP: ${response.status}`);
}
}
const data = await response.json();
// Gestione errori API
if (data.error) {
throw new Error(`Errore API: ${data.error.message}`);
}
return data;
} catch (error) {
console.error('Errore:', error.message);
throw error;
}
}
|
Best Practices
- Gestione degli errori: Implementare sempre una gestione degli errori robusta
- Rate Limiting: Rispettare i limiti di frequenza delle richieste API
- Caching: Memorizzare nella cache le risposte per ridurre le chiamate API
- Retry con backoff esponenziale: In caso di errori temporanei, implementare un sistema di retry con attese crescenti
- Validazione input: Verificare sempre i dati di input prima di inviarli alle API
- Logging: Registrare le richieste e le risposte per il debug
- Timeout: Impostare timeout adeguati per le richieste API
Supporto
Per assistenza tecnica nell'implementazione delle API, contattare formedil@formedil.it.