Documentazione API

Riferimento completo per integrare l'API di conversione estratti conto Balanzio

Introduzione

L'API Balanzio ti consente di convertire PDF di estratti conto in formati di dati strutturati (CSV, XLSX, JSON). La nostra API supporta sia PDF testuali che basati su immagini (scansionati) con elaborazione OCR.

Elaborazione Veloce

PDF testuali in pochi secondi, OCR in <30s per pagina

Sicuro e Conforme al GDPR

Eliminazione automatica dopo 24h

Supporto Multi-Banca

Oltre 100 banche supportate

Autenticazione

Tutte le richieste API richiedono autenticazione tramite un token Bearer. Includi la tua chiave API nell'intestazione Authorization:

HTTP
Authorization: Bearer YOUR_API_KEY
Mantieni la tua chiave API segreta!

Non esporre mai la tua chiave API nel codice lato client o inserirla nel controllo versione.

Endpoint

URL Base

https://api.balanzio.app/api/v1

Carica Estratto Conto

POST
/bank-statement

Carica uno o più file PDF per l'elaborazione. L'API rileverà automaticamente se il PDF è testuale o basato su immagine (scansionato).

Parametri della Richiesta

ParametroTipoRichiestoDescrizione
filesfile[]File PDF da elaborare (max 3MB ciascuno)

Esempio di Richiesta

curl
curl -X POST https://api.balanzio.app/api/v1/bank-statement \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -F "files=@statement.pdf"

Risposta (201 Created)

json
[
  {
    "uuid": "550e8400-e29b-41d4-a716-446655440000",
    "filename": "statement.pdf",
    "pdfType": "TEXT_BASED",
    "state": "READY",
    "numberOfPages": 3
  }
]

Campi della Risposta

CampoTipoDescrizione
uuidstringIdentificatore univoco per il file caricato
filenamestringNome file originale
pdfTypestringTEXT_BASED o IMAGE_BASED
statestringREADY (testo) o PROCESSING (OCR)
numberOfPagesnumberTotale pagine nel PDF

Verifica Stato Elaborazione

POST
/bank-statement/status

Verifica lo stato di elaborazione dei file caricati. Utilizza questo endpoint per verificare il completamento dell'OCR.

Esempio di Richiesta

curl
curl -X POST https://api.balanzio.app/api/v1/bank-statement/status \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "uuids": ["550e8400-e29b-41d4-a716-446655440000"]
  }'

Risposta (200 OK)

json
[
  {
    "uuid": "550e8400-e29b-41d4-a716-446655440000",
    "filename": "statement.pdf",
    "pdfType": "IMAGE_BASED",
    "state": "COMPLETED",
    "numberOfPages": 3,
    "progress": 100
  }
]

Converti in Formato

POST
/bank-statement/convert

Converti gli estratti conto elaborati in formato CSV, XLSX o JSON.

Parametri Query

ParametroTipoRichiestoDescrizione
formatstringCSV, XLSX o JSON

Esempio di Richiesta (CSV)

curl
curl -X POST "https://api.balanzio.app/api/v1/bank-statement/convert?format=CSV" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "uuid": "550e8400-e29b-41d4-a716-446655440000"
  }' \
  -o statement.csv

Esempio di Richiesta (JSON)

curl
curl -X POST "https://api.balanzio.app/api/v1/bank-statement/convert?format=JSON" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "uuid": "550e8400-e29b-41d4-a716-446655440000"
  }'

Risposta (formato JSON)

json
{
  "transactions": [
    {
      "date": "2024-01-15",
      "description": "VIREMENT SALAIRE",
      "amount": 3500.00,
      "balance": 4250.50,
      "currency": "EUR"
    },
    {
      "date": "2024-01-16",
      "description": "CARTE 12/01 SUPERMARCHE",
      "amount": -85.30,
      "balance": 4165.20,
      "currency": "EUR"
    }
  ],
  "metadata": {
    "bank": "BNP Paribas",
    "accountNumber": "****1234",
    "statementPeriod": "2024-01"
  },
  "warnings": []
}

Imposta Password PDF

POST
/bank-statement/set-password

Fornisci la password per PDF protetti da password.

Esempio di Richiesta

curl
curl -X POST https://api.balanzio.app/api/v1/bank-statement/set-password \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "uuid": "550e8400-e29b-41d4-a716-446655440000",
    "password": "mySecretPassword123"
  }'

Risposta (200 OK)

json
{
  "uuid": "550e8400-e29b-41d4-a716-446655440000",
  "state": "READY",
  "passwordSet": true
}

Ottieni Informazioni Utente

GET
/user

Recupera le informazioni dell'utente corrente, inclusi crediti e dettagli del piano.

Esempio di Richiesta

curl
curl -X GET https://api.balanzio.app/api/v1/user \
  -H "Authorization: Bearer YOUR_API_KEY"

Risposta (200 OK)

json
{
  "user": {
    "userId": 123,
    "firstName": "John",
    "lastName": "Doe",
    "email": "john@example.com",
    "emailVerified": true,
    "referralCode": "ABC123"
  },
  "credits": {
    "paidCredits": 1000,
    "freeCredits": 50
  },
  "unlimitedCredits": false,
  "subscriptionCount": 1,
  "plan": "pro",
  "saveConvertedFiles": false,
  "hasPaymentMethod": true
}

Codici di Errore

Tutti gli errori restituiscono una risposta JSON con un codice di errore e un messaggio:

json
{
  "error": "INVALID_FILE_TYPE",
  "message": "Only PDF files are accepted",
  "recovery": "Please upload a PDF file"
}
StatoCodice di ErroreDescrizione
400
INVALID_FILE_TYPEIl file non è un PDF
400
INVALID_FORMATParametro formato non valido (deve essere CSV, XLSX o JSON)
401
UNAUTHORIZEDChiave API non valida o mancante
403
INSUFFICIENT_CREDITSCrediti insufficienti per elaborare il file
404
FILE_NOT_FOUNDUUID file non trovato
413
FILE_TOO_LARGEIl file supera il limite di 3MB
422
PASSWORD_REQUIREDIl PDF è protetto da password
422
INVALID_PASSWORDPassword PDF errata
429
RATE_LIMIT_EXCEEDEDTroppe richieste
500
INTERNAL_ERRORErrore del server, riprova

Limiti di Velocità

Utenti Anonimi

10 richieste al minuto

1 pagina al giorno

Nessun caricamento simultaneo

Utenti Autenticati

60 richieste al minuto

Basato su crediti (dipende dal piano)

Fino a 5 caricamenti simultanei

Intestazioni limite di velocità: Tutte le risposte includono le intestazioni X-RateLimit-Limit, X-RateLimit-Remaining e X-RateLimit-Reset.

Esempi di Codice Completi

Python

python
import requests
import time

API_KEY = "YOUR_API_KEY"
BASE_URL = "https://api.balanzio.app/api/v1"
HEADERS = {"Authorization": f"Bearer {API_KEY}"}

# 1. Upload PDF
with open("statement.pdf", "rb") as f:
    files = {"files": f}
    response = requests.post(
        f"{BASE_URL}/bank-statement",
        headers=HEADERS,
        files=files
    )
    data = response.json()
    file_uuid = data[0]["uuid"]
    pdf_type = data[0]["pdfType"]
    print(f"Uploaded: {file_uuid} ({pdf_type})")

# 2. Poll status if OCR is needed
if pdf_type == "IMAGE_BASED":
    while True:
        response = requests.post(
            f"{BASE_URL}/bank-statement/status",
            headers=HEADERS,
            json={"uuids": [file_uuid]}
        )
        status = response.json()[0]
        if status["state"] == "COMPLETED":
            print("Processing complete!")
            break
        elif status["state"] == "ERROR":
            print("Processing failed:", status.get("error"))
            break
        print(f"Progress: {status.get('progress', 0)}%")
        time.sleep(3)

# 3. Convert to JSON
response = requests.post(
    f"{BASE_URL}/bank-statement/convert",
    headers=HEADERS,
    params={"format": "JSON"},
    json={"uuid": file_uuid}
)

transactions = response.json()
print(f"Found {len(transactions['transactions'])} transactions")
for txn in transactions["transactions"]:
    print(f"{txn['date']}: {txn['description']} - {txn['amount']} {txn['currency']}")

Node.js

javascript
const FormData = require('form-data');
const fs = require('fs');
const fetch = require('node-fetch');

const API_KEY = 'YOUR_API_KEY';
const BASE_URL = 'https://api.balanzio.app/api/v1';
const HEADERS = { 'Authorization': `Bearer ${API_KEY}` };

async function convertBankStatement() {
  // 1. Upload PDF
  const form = new FormData();
  form.append('files', fs.createReadStream('statement.pdf'));

  let response = await fetch(`${BASE_URL}/bank-statement`, {
    method: 'POST',
    headers: HEADERS,
    body: form
  });

  const uploadData = await response.json();
  const fileUuid = uploadData[0].uuid;
  const pdfType = uploadData[0].pdfType;
  console.log(`Uploaded: ${fileUuid} (${pdfType})`);

  // 2. Poll status if OCR needed
  if (pdfType === 'IMAGE_BASED') {
    let completed = false;
    while (!completed) {
      response = await fetch(`${BASE_URL}/bank-statement/status`, {
        method: 'POST',
        headers: { ...HEADERS, 'Content-Type': 'application/json' },
        body: JSON.stringify({ uuids: [fileUuid] })
      });

      const statusData = await response.json();
      const status = statusData[0];

      if (status.state === 'COMPLETED') {
        console.log('Processing complete!');
        completed = true;
      } else if (status.state === 'ERROR') {
        throw new Error(`Processing failed: ${status.error}`);
      } else {
        console.log(`Progress: ${status.progress || 0}%`);
        await new Promise(resolve => setTimeout(resolve, 3000));
      }
    }
  }

  // 3. Convert to JSON
  response = await fetch(
    `${BASE_URL}/bank-statement/convert?format=JSON`,
    {
      method: 'POST',
      headers: { ...HEADERS, 'Content-Type': 'application/json' },
      body: JSON.stringify({ uuid: fileUuid })
    }
  );

  const transactions = await response.json();
  console.log(`Found ${transactions.transactions.length} transactions`);

  transactions.transactions.forEach(txn => {
    console.log(`${txn.date}: ${txn.description} - ${txn.amount} ${txn.currency}`);
  });
}

convertBankStatement().catch(console.error);

PHP

php
<?php

$apiKey = 'YOUR_API_KEY';
$baseUrl = 'https://api.balanzio.app/api/v1';

// 1. Upload PDF
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "$baseUrl/bank-statement");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Authorization: Bearer $apiKey"
]);

$file = new CURLFile('statement.pdf', 'application/pdf', 'statement.pdf');
curl_setopt($ch, CURLOPT_POSTFIELDS, ['files' => $file]);

$response = curl_exec($ch);
$data = json_decode($response, true);
$fileUuid = $data[0]['uuid'];
$pdfType = $data[0]['pdfType'];

echo "Uploaded: $fileUuid ($pdfType)\n";

// 2. Poll status if OCR needed
if ($pdfType === 'IMAGE_BASED') {
    do {
        sleep(3);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "$baseUrl/bank-statement/status");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            "Authorization: Bearer $apiKey",
            "Content-Type: application/json"
        ]);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
            'uuids' => [$fileUuid]
        ]));

        $response = curl_exec($ch);
        $statusData = json_decode($response, true);
        $status = $statusData[0];

        echo "Progress: " . ($status['progress'] ?? 0) . "%\n";
    } while ($status['state'] !== 'COMPLETED' && $status['state'] !== 'ERROR');

    echo "Processing complete!\n";
}

// 3. Convert to JSON
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "$baseUrl/bank-statement/convert?format=JSON");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Authorization: Bearer $apiKey",
    "Content-Type: application/json"
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
    'uuid' => $fileUuid
]));

$response = curl_exec($ch);
$transactions = json_decode($response, true);

echo "Found " . count($transactions['transactions']) . " transactions\n";

foreach ($transactions['transactions'] as $txn) {
    echo "{$txn['date']}: {$txn['description']} - {$txn['amount']} {$txn['currency']}\n";
}

curl_close($ch);
?>

Hai Bisogno di Aiuto?

Supporto

Il nostro team di supporto è qui per aiutarti a integrare con successo.

Collezione Postman

Scarica la nostra collezione Postman per testare facilmente tutti gli endpoint.