> ## Documentation Index
> Fetch the complete documentation index at: https://docs.abbyy.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Traiter via l’API

> Guide de démarrage rapide pas à pas pour traiter un document avec l’API REST d’ABBYY Vantage : authentifiez-vous, choisissez une compétence, téléversez un fichier et téléchargez les données JSON extraites.

export const VantageRegion = ({children}) => {
  const STORAGE_KEY = "abbyy.vantage.region";
  const REGIONS = [{
    code: "eu",
    label: "Europe"
  }, {
    code: "us",
    label: "North America"
  }, {
    code: "au",
    label: "Australia / Asia-Pacific"
  }];
  const [region, setRegion] = useState("eu");
  const [open, setOpen] = useState(false);
  const containerRef = useRef(null);
  const dropdownRef = useRef(null);
  function safeGetSavedRegion() {
    try {
      const saved = typeof window !== "undefined" ? window.localStorage.getItem(STORAGE_KEY) : null;
      const valid = new Set(REGIONS.map(r => r.code));
      return saved && valid.has(saved) ? saved : "eu";
    } catch {
      return "eu";
    }
  }
  function safeSetSavedRegion(code) {
    try {
      if (typeof window !== "undefined") {
        window.localStorage.setItem(STORAGE_KEY, code);
      }
    } catch {}
  }
  function dispatchRegionChanged(code) {
    try {
      if (typeof window !== "undefined") {
        window.dispatchEvent(new CustomEvent("abbyy:region-changed", {
          detail: {
            code
          }
        }));
      }
    } catch {}
  }
  function replaceRegionInString(text, currentRegion) {
    if (typeof text !== "string") return text;
    const hostRegex = /https:\/\/vantage-(eu|us|au)\.abbyy\.com/gi;
    const tokenRegex = /https:\/\/vantage-\[region\]\.abbyy\.com/gi;
    const bareHostRegex = /vantage-(eu|us|au)\.abbyy\.com/gi;
    const bareTokenRegex = /vantage-\[region\]\.abbyy\.com/gi;
    return text.replace(hostRegex, `https://vantage-${currentRegion}.abbyy.com`).replace(tokenRegex, `https://vantage-${currentRegion}.abbyy.com`).replace(bareHostRegex, `vantage-${currentRegion}.abbyy.com`).replace(bareTokenRegex, `vantage-${currentRegion}.abbyy.com`);
  }
  useEffect(() => {
    setRegion(safeGetSavedRegion());
  }, []);
  useEffect(() => {
    const root = containerRef.current;
    if (!root) return;
    const anchors = root.querySelectorAll("a[href]");
    anchors.forEach(a => {
      const href = a.getAttribute("href");
      if (href) {
        const next = replaceRegionInString(href, region);
        if (next !== href) {
          a.setAttribute("href", next);
        }
      }
    });
    const walker = typeof document !== "undefined" ? document.createTreeWalker(root, NodeFilter.SHOW_TEXT, null) : null;
    if (walker) {
      const toUpdate = [];
      let node = walker.nextNode();
      while (node) {
        const updated = replaceRegionInString(node.nodeValue, region);
        if (updated !== node.nodeValue) {
          toUpdate.push([node, updated]);
        }
        node = walker.nextNode();
      }
      toUpdate.forEach(([textNode, value]) => {
        textNode.nodeValue = value;
      });
    }
  }, [region, children]);
  useEffect(() => {
    const root = containerRef.current;
    if (!root) return;
    const anchors = root.querySelectorAll("a[href]");
    anchors.forEach(a => {
      a.style.fontWeight = "600";
      a.style.textDecoration = "underline";
      a.style.textUnderlineOffset = "2px";
    });
  }, [region, children]);
  useEffect(() => {
    const onRegionChanged = evt => {
      const code = evt && evt.detail && evt.detail.code;
      if (!code || code === region) return;
      setRegion(code);
    };
    if (typeof window !== "undefined") {
      window.addEventListener("abbyy:region-changed", onRegionChanged);
    }
    return () => {
      if (typeof window !== "undefined") {
        window.removeEventListener("abbyy:region-changed", onRegionChanged);
      }
    };
  }, [region]);
  useEffect(() => {
    const onClickAway = e => {
      if (!dropdownRef.current) return;
      if (!dropdownRef.current.contains(e.target)) {
        setOpen(false);
      }
    };
    document.addEventListener("click", onClickAway, true);
    return () => document.removeEventListener("click", onClickAway, true);
  }, []);
  const onSelect = code => {
    setRegion(code);
    safeSetSavedRegion(code);
    dispatchRegionChanged(code);
    setOpen(false);
  };
  const current = REGIONS.find(r => r.code === region) || REGIONS[0];
  return <div className="not-prose">
      <div className="mb-4 inline-flex items-center gap-2" ref={dropdownRef}>
        <span className="text-sm text-zinc-950/80 dark:text-white/80">Tenant Region:</span>
        <div className="relative">
          <button type="button" aria-haspopup="listbox" aria-expanded={open ? "true" : "false"} onClick={() => setOpen(v => !v)} className="h-8 px-3 rounded-md bg-zinc-900/5 dark:bg-white/5 border border-zinc-950/20 dark:border-white/20 text-sm inline-flex items-center gap-2">
            <span className="text-zinc-950 dark:text-white">{current.label}</span>
            <svg width="8" height="24" viewBox="0 -9 3 24" className="transition-transform text-gray-400 overflow-visible dark:text-gray-600 ml-auto" style={{
    transform: open ? "rotate(270deg)" : "rotate(90deg)"
  }}>
              <path d="M0 0L3 3L0 6" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"></path>
            </svg>
          </button>
          {open ? <div role="listbox" className="absolute z-50 left-full top-0 ml-2 w-56 rounded-xl border border-zinc-950/20 dark:border-white/20 bg-white dark:bg-zinc-900 shadow-lg p-2">
              {REGIONS.map(r => {
    const selected = r.code === region;
    return <button key={r.code} type="button" role="option" aria-selected={selected ? "true" : "false"} onClick={() => onSelect(r.code)} className={"w-full flex items-center justify-between px-3 py-2 rounded-lg text-sm hover:bg-zinc-950/5 dark:hover:bg-white/10 text-zinc-950 dark:text-white" + (selected ? " font-medium" : "")}>
                    <span style={selected ? {
      color: "#ff2038"
    } : undefined}>{r.label}</span>
                    <span className={selected ? "ml-3" : "ml-3 invisible"} style={selected ? {
      color: "#ff2038"
    } : undefined}>✓</span>
                  </button>;
  })}
            </div> : null}
        </div>
      </div>
      <div ref={containerRef} className="prose dark:prose-invert max-w-none">{children}</div>
    </div>;
};

<VantageRegion>
  Ce guide vous accompagne pas à pas dans le workflow de l'API Vantage : authentifiez-vous, trouvez une compétence, téléversez un document et téléchargez les résultats structurés.

  **Ce que vous allez accomplir :** Soumettre un document à l'API REST Vantage et recevoir des données extraites structurées au format JSON.

  **Durée estimée :** \~10 minutes

  ## Prérequis

  * Un tenant Vantage avec des identifiants d’un client API (`client_id` et `client_secret`)
  * Un exemple de document à traiter (PDF, TIFF, JPEG ou PNG)

  <Callout type="info">
    Vous n'avez pas encore d'identifiants ? Votre administrateur de tenant peut créer des identifiants client API dans **Administration > Clients API**.
  </Callout>

  ## Étape 1 : S'authentifier

  Obtenez un jeton d'accès à l'aide de vos identifiants client.

  <Tabs>
    <Tab title="cURL">
      ```bash theme={null}
      curl -X POST "https://vantage-us.abbyy.com/auth2/connect/token" \
        -d "grant_type=client_credentials" \
        -d "scope=openid permissions global.wildcard" \
        -d "client_id=YOUR_CLIENT_ID" \
        -d "client_secret=YOUR_CLIENT_SECRET"
      ```
    </Tab>

    <Tab title="Python">
      ```python theme={null}
      import requests

      response = requests.post(
          "https://vantage-us.abbyy.com/auth2/connect/token",
          data={
              "grant_type": "client_credentials",
              "scope": "openid permissions global.wildcard",
              "client_id": "YOUR_CLIENT_ID",
              "client_secret": "YOUR_CLIENT_SECRET",
          },
      )

      token = response.json()["access_token"]
      ```
    </Tab>
  </Tabs>

  La réponse inclut un `access_token` (valide 24 heures). Utilisez-le dans l'en-tête `Authorization` pour toutes les requêtes ultérieures.

  <Callout type="tip">
    Utilisez le sélecteur **Tenant Region** en haut de cette page pour mettre à jour toutes les URL afin qu’elles correspondent à votre région.
  </Callout>

  ## Étape 2 : Trouver une compétence

  Répertoriez les compétences disponibles dans votre tenant pour trouver celle qui correspond à votre document.

  <Tabs>
    <Tab title="cURL">
      ```bash theme={null}
      curl -X GET "https://vantage-us.abbyy.com/api/publicapi/v1/skills" \
        -H "Authorization: Bearer $TOKEN"
      ```
    </Tab>

    <Tab title="Python">
      ```python theme={null}
      skills = requests.get(
          "https://vantage-us.abbyy.com/api/publicapi/v1/skills",
          headers={"Authorization": f"Bearer {token}"},
      ).json()

      for skill in skills:
          print(f"{skill['id']}: {skill['name']}")
      ```
    </Tab>
  </Tabs>

  Notez l'`id` de la compétence que vous souhaitez utiliser (par exemple, une compétence Invoice).

  ## Étape 3 : Traiter un document

  Téléversez un document et traitez-le avec une compétence en un seul appel API.

  <Tabs>
    <Tab title="cURL">
      ```bash theme={null}
      curl -X POST "https://vantage-us.abbyy.com/api/publicapi/v1/transactions/launch?skillId=SKILL_ID" \
        -H "Authorization: Bearer $TOKEN" \
        -H "Content-Type: multipart/form-data" \
        -F 'Model={"files": [{}]}' \
        -F "Files=@invoice.pdf;type=application/pdf"
      ```
    </Tab>

    <Tab title="Python">
      ```python theme={null}
      with open("invoice.pdf", "rb") as f:
          response = requests.post(
              "https://vantage-us.abbyy.com/api/publicapi/v1/transactions/launch",
              params={"skillId": "SKILL_ID"},
              headers={"Authorization": f"Bearer {token}"},
              files={
                  "Model": (None, '{"files": [{}]}', "application/json"),
                  "Files": ("invoice.pdf", f, "application/pdf"),
              },
          )

      transaction_id = response.json()["transactionId"]
      ```
    </Tab>
  </Tabs>

  ## Étape 4 : Vérifier le statut

  Interrogez la transaction jusqu'à la fin du traitement.

  <Tabs>
    <Tab title="cURL">
      ```bash theme={null}
      curl -X GET "https://vantage-us.abbyy.com/api/publicapi/v1/transactions/$TRANSACTION_ID" \
        -H "Authorization: Bearer $TOKEN"
      ```
    </Tab>

    <Tab title="Python">
      ```python theme={null}
      import time

      while True:
          status = requests.get(
              f"https://vantage-us.abbyy.com/api/publicapi/v1/transactions/{transaction_id}",
              headers={"Authorization": f"Bearer {token}"},
          ).json()

          print(f"Status: {status['status']}")

          if status["status"] in ("Processed", "ProcessedWithWarnings"):
              break
          if status["status"] == "NotProcessed":
              raise Exception("Processing failed")

          time.sleep(5)
      ```
    </Tab>
  </Tabs>

  <Callout type="info">
    Interrogez toutes les 5 à 10 secondes. Le traitement prend généralement 10 à 30 secondes, selon la complexité du document.
  </Callout>

  ## Étape 5 : Télécharger les résultats

  Obtenez les données extraites au format JSON.

  <Tabs>
    <Tab title="cURL">
      ```bash theme={null}
      # Lister les documents de la transaction
      curl -X GET "https://vantage-us.abbyy.com/api/publicapi/v1/transactions/$TRANSACTION_ID/documents" \
        -H "Authorization: Bearer $TOKEN"

      # Télécharger le fichier de résultat
      curl -X GET "https://vantage-us.abbyy.com/api/publicapi/v1/transactions/$TRANSACTION_ID/files/$FILE_ID/download" \
        -H "Authorization: Bearer $TOKEN" \
        -o result.json
      ```
    </Tab>

    <Tab title="Python">
      ```python theme={null}
      # Récupérer les documents
      docs = requests.get(
          f"https://vantage-us.abbyy.com/api/publicapi/v1/transactions/{transaction_id}/documents",
          headers={"Authorization": f"Bearer {token}"},
      ).json()

      # Télécharger le résultat du premier document
      result_file_id = docs[0]["resultFiles"][0]["id"]

      result = requests.get(
          f"https://vantage-us.abbyy.com/api/publicapi/v1/transactions/{transaction_id}/files/{result_file_id}/download",
          headers={"Authorization": f"Bearer {token}"},
      ).json()

      print(result)
      ```
    </Tab>
  </Tabs>

  Le résultat contient des champs extraits avec leurs valeurs et scores de confiance.

  <Expandable title="Exemple : résultat de l’extraction d’une facture">
    ```json theme={null}
    {
      "SkillName": "ABBYY Invoice",
      "Documents": [
        {
          "ExtractedData": {
            "RootObject": {
              "Fields": [
                {
                  "Name": "InvoiceNumber",
                  "List": [{
                    "Value": "INV-2024-0042",
                    "Annotation": { "Confidence": 97, "RawValue": "INV-2024-0042" },
                    "NeedVerification": false
                  }]
                },
                {
                  "Name": "VendorName",
                  "List": [{
                    "Value": "Acme Corp",
                    "Annotation": { "Confidence": 95, "RawValue": "Acme Corp" },
                    "NeedVerification": false
                  }]
                },
                {
                  "Name": "TotalAmount",
                  "List": [{
                    "Value": "1,250.00",
                    "Annotation": { "Confidence": 88, "RawValue": "1,250.00" },
                    "NeedVerification": false
                  }]
                }
              ]
            }
          }
        }
      ]
    }
    ```
  </Expandable>

  Chaque champ comprend une `Value` (le texte extrait après normalisation), un score `Annotation.Confidence` de 0 à 100, ainsi qu'un indicateur `NeedVerification` précisant si une vérification humaine est recommandée. Les champs dont le niveau de confiance est faible ou dont les règles de validation ont échoué sont automatiquement signalés.

  Pour une présentation complète de la structure de sortie, consultez [Comprendre vos résultats](/fr/vantage/getting-started/results).

  ## Exemple complet

  <Expandable title="Script complet en Python">
    ```python theme={null}
    import requests
    import time

    # Configuration
    BASE_URL = "https://vantage-us.abbyy.com"
    CLIENT_ID = "YOUR_CLIENT_ID"
    CLIENT_SECRET = "YOUR_CLIENT_SECRET"
    SKILL_ID = "YOUR_SKILL_ID"
    FILE_PATH = "invoice.pdf"

    # Étape 1 : Authentification
    auth = requests.post(
        f"{BASE_URL}/auth2/connect/token",
        data={
            "grant_type": "client_credentials",
            "scope": "openid permissions global.wildcard",
            "client_id": CLIENT_ID,
            "client_secret": CLIENT_SECRET,
        },
    )
    token = auth.json()["access_token"]
    headers = {"Authorization": f"Bearer {token}"}

    # Étape 2 : Rechercher les compétences
    skills = requests.get(f"{BASE_URL}/api/publicapi/v1/skills", headers=headers).json()
    print(f"Available skills: {[s['name'] for s in skills]}")

    # Étape 3 : Traiter le document
    with open(FILE_PATH, "rb") as f:
        launch = requests.post(
            f"{BASE_URL}/api/publicapi/v1/transactions/launch",
            params={"skillId": SKILL_ID},
            headers=headers,
            files={
                "Model": (None, '{"files": [{}]}', "application/json"),
                "Files": (FILE_PATH, f, "application/pdf"),
            },
        )
    transaction_id = launch.json()["transactionId"]
    print(f"Transaction: {transaction_id}")

    # Étape 4 : Interroger jusqu'à la fin du traitement
    while True:
        tx = requests.get(
            f"{BASE_URL}/api/publicapi/v1/transactions/{transaction_id}",
            headers=headers,
        ).json()
        print(f"Status: {tx['status']}")
        if tx["status"] in ("Processed", "ProcessedWithWarnings"):
            break
        if tx["status"] == "NotProcessed":
            raise Exception(f"Processing failed")
        time.sleep(5)

    # Étape 5 : Télécharger les résultats
    docs = requests.get(
        f"{BASE_URL}/api/publicapi/v1/transactions/{transaction_id}/documents",
        headers=headers,
    ).json()

    for doc in docs:
        for rf in doc.get("resultFiles", []):
            result = requests.get(
                f"{BASE_URL}/api/publicapi/v1/transactions/{transaction_id}/files/{rf['id']}/download",
                headers=headers,
            ).json()
            print(result)
    ```
  </Expandable>

  ## Étapes suivantes

  <CardGroup cols={2}>
    <Card title="Comprendre vos résultats" icon="magnifying-glass" href="/fr/vantage/getting-started/results">
      Découvrez comment interpréter les champs extraits, les scores de confiance et les données de tableau.
    </Card>

    <Card title="Référence de l’API" icon="rectangle-terminal" href="/fr/vantage/developer/api-introduction">
      Documentation complète de l’API avec environnement de test interactif.
    </Card>

    <Card title="Options d’authentification" icon="lock" href="/fr/vantage/developer/authentication/authentication">
      Flux Authorization Code, ROPC et autres méthodes d’authentification.
    </Card>

    <Card title="Traitement par lot" icon="layer-group" href="/fr/vantage/developer/processing-documents/processing-documents-with-separate-api-calls">
      Traitez plusieurs documents avec des appels d’API distincts pour un meilleur contrôle.
    </Card>
  </CardGroup>
</VantageRegion>
