---
title: Recettes d'intégration
description: Exemples complets avec curl, fetch, Python et GitHub Actions pour demander et suivre exécutions, audits, rapports et consommation.
---

# Recettes d'intégration

Ces recettes couvrent les intégrations les plus courantes. Elles utilisent l'hôte d'exemple `maintain.example` et la variable `$MAINTAIN_API_KEY` : remplacez-les par votre instance et votre clé.

**Qui peut le faire** : un intégrateur muni d'une clé dont les droits correspondent à la recette (indiqués en tête de chaque section). Voir [Clés API personnelles](02-cles-api-personnelles.md).

## Avant de commencer

Récupérez les identifiants dont les recettes ont besoin :

```bash
export MAINTAIN_URL=https://maintain.example
# Projets accessibles (droit : Lire les projets)
curl -sS "$MAINTAIN_URL/api/v1/projects" -H "Authorization: Bearer $MAINTAIN_API_KEY" | jq '.projects'
# Dépôts d'un projet (droit : Lire les dépôts)
curl -sS "$MAINTAIN_URL/api/v1/projects/<projectId>/repositories" \
  -H "Authorization: Bearer $MAINTAIN_API_KEY" | jq '.repositories'
```

Une exécution porte sur une issue **déjà reçue** par la plateforme : le dépôt doit être lié à la GitHub App et surveillé. Voir [Réception des issues GitHub](../02-projets-et-depots/08-reception-des-issues.md).

## curl : demander et suivre une exécution

Droits : Démarrer une exécution, Lire les exécutions, Annuler une exécution.

```bash
PROJECT=<projectId>
REPO=<repositoryId>
ISSUE=42

# 1. Demande (la même Idempotency-Key permet de réessayer sans doublon)
curl -sS -i -X POST "$MAINTAIN_URL/api/v1/projects/$PROJECT/runs" \
  -H "Authorization: Bearer $MAINTAIN_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: issue-$ISSUE-$(date -u +%F)" \
  -d "{\"repositoryId\":\"$REPO\",\"issueNumber\":$ISSUE}"

# 2. Suivi : remplacez <runId> par l'identifiant reçu (en-tête Location)
curl -sS "$MAINTAIN_URL/api/v1/runs/<runId>" \
  -H "Authorization: Bearer $MAINTAIN_API_KEY" | jq '{status, result, publication}'

# 3. Annulation si besoin (idempotente)
curl -sS -X POST "$MAINTAIN_URL/api/v1/runs/<runId>/cancel" \
  -H "Authorization: Bearer $MAINTAIN_API_KEY"
```

Statuts terminaux : `prepared`, `needs_input`, `refused`, `failed`, `unknown`, `canceled`. Un statut `queued` accompagné de `waiting: "organization_stop"` signale un arrêt global : l'exécution démarrera après la levée. Avec `prepared`, `result.changedFiles` liste les fichiers modifiés et `publication.pullNumber` donne la PR brouillon quand elle est ouverte. `result.testsExecuted` vaut toujours `false` : les tests du dépôt ne sont pas exécutés.

## curl : télécharger un rapport d'incident

Droit : Lire les rapports. Le rapport doit avoir été généré dans l'interface.

```bash
curl -sS -D headers.txt -o rapport.pdf "$MAINTAIN_URL/api/v1/runs/<runId>/report" \
  -H "Authorization: Bearer $MAINTAIN_API_KEY"
expected=$(grep -i '^x-report-sha256:' headers.txt | awk '{print $2}' | tr -d '\r')
echo "$expected  rapport.pdf" | shasum -a 256 -c -
```

## JavaScript (fetch, Node.js 18 ou plus)

Droits : Démarrer une exécution, Lire les exécutions. Le script gère le quota (`429`) et l'exécution déjà existante (`409`).

```js
const base = process.env.MAINTAIN_URL ?? 'https://maintain.example'
const key = process.env.MAINTAIN_API_KEY
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
const terminal = new Set(['prepared', 'needs_input', 'refused', 'failed', 'unknown', 'canceled'])

async function api(path, init = {}) {
  for (;;) {
    const response = await fetch(base + path, {
      ...init,
      headers: { Authorization: `Bearer ${key}`, ...init.headers },
    })
    if (response.status === 429) {
      await sleep(Number(response.headers.get('Retry-After') ?? 60) * 1000)
      continue
    }
    const body = await response.json()
    return { status: response.status, headers: response.headers, body }
  }
}

export async function runIssue(projectId, repositoryId, issueNumber) {
  const created = await api(`/api/v1/projects/${projectId}/runs`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Idempotency-Key': `issue-${repositoryId}-${issueNumber}`,
    },
    body: JSON.stringify({ repositoryId, issueNumber }),
  })
  let path
  if (created.status === 202) path = created.headers.get('Location')
  else if (created.status === 409 && created.body.existingRun) path = created.body.existingRun.links.self
  else throw new Error(`${created.status} ${created.body.error}: ${created.body.message}`)

  for (;;) {
    const { body: run } = await api(path)
    if (terminal.has(run.status)) return run
    if (run.nextAttempt) path = `/api/v1/runs/${run.nextAttempt.id}`
    await sleep(15_000)
  }
}
```

## Python : audit hebdomadaire et rapport final

Droits : Demander un audit, Lire les audits, Lire les rapports. Bibliothèque standard uniquement.

```python
import datetime, json, os, time, urllib.error, urllib.request

BASE = os.environ.get("MAINTAIN_URL", "https://maintain.example")
KEY = os.environ["MAINTAIN_API_KEY"]

def call(method, path, body=None, headers=None):
    data = json.dumps(body).encode() if body is not None else None
    request = urllib.request.Request(BASE + path, data=data, method=method)
    request.add_header("Authorization", f"Bearer {KEY}")
    if body is not None:
        request.add_header("Content-Type", "application/json")
    for name, value in (headers or {}).items():
        request.add_header(name, value)
    while True:
        try:
            with urllib.request.urlopen(request) as response:
                return response.status, json.load(response)
        except urllib.error.HTTPError as error:
            if error.code == 429:
                time.sleep(int(error.headers.get("Retry-After", "60")))
                continue
            return error.code, json.load(error)

def weekly_audit(project_id, repository_id):
    week = datetime.date.today().strftime("%G-W%V")
    status, audit = call("POST", f"/api/v1/projects/{project_id}/audits",
                         {"repositoryId": repository_id},
                         {"Idempotency-Key": f"audit-{repository_id}-{week}"})
    if status != 202:
        raise SystemExit(f"{status} {audit['error']}: {audit['message']}")
    while audit["status"] in ("queued", "running"):
        time.sleep(30)
        _, audit = call("GET", audit["links"]["self"])
    print(audit["status"], len(audit.get("findings", [])), "constat(s)")
    status, report = call("GET", f"/api/v1/audits/{audit['id']}/report")
    if status == 409:
        print("Constats à qualifier dans l'interface avant le rapport final.")
    elif status == 200:
        for finding in report["findings"]:
            print(finding["rule"], finding["location"])
```

## GitHub Actions : demander une exécution depuis un dépôt

Droits : Démarrer une exécution, Lire les exécutions. Enregistrez la clé dans le secret `MAINTAIN_API_KEY` du dépôt, et les identifiants dans les variables `MAINTAIN_URL`, `MAINTAIN_PROJECT_ID` et `MAINTAIN_REPOSITORY_ID`.

```yaml
name: 101Maintain
on:
  workflow_dispatch:
    inputs:
      issue:
        description: Numéro de l'issue à traiter
        required: true
        type: number

jobs:
  run:
    runs-on: ubuntu-latest
    timeout-minutes: 60
    env:
      MAINTAIN_URL: ${{ vars.MAINTAIN_URL }}
      MAINTAIN_API_KEY: ${{ secrets.MAINTAIN_API_KEY }}
    steps:
      - name: Demander l'exécution
        id: request
        run: |
          code=$(curl -sS -o body.json -w '%{http_code}' -X POST \
            "$MAINTAIN_URL/api/v1/projects/${{ vars.MAINTAIN_PROJECT_ID }}/runs" \
            -H "Authorization: Bearer $MAINTAIN_API_KEY" \
            -H "Content-Type: application/json" \
            -H "Idempotency-Key: gha-${{ github.run_id }}" \
            -d '{"repositoryId":"${{ vars.MAINTAIN_REPOSITORY_ID }}","issueNumber":${{ inputs.issue }}}')
          case "$code" in
            202) path=$(jq -r '.links.self' body.json) ;;
            409) path=$(jq -r '.existingRun.links.self // empty' body.json) ;;
          esac
          if [ -z "${path:-}" ]; then cat body.json; exit 1; fi
          echo "path=$path" >> "$GITHUB_OUTPUT"
      - name: Attendre le résultat
        run: |
          while :; do
            run=$(curl -sS "$MAINTAIN_URL${{ steps.request.outputs.path }}" \
              -H "Authorization: Bearer $MAINTAIN_API_KEY")
            status=$(echo "$run" | jq -r '.status')
            case "$status" in queued|running) sleep 30 ;; *) break ;; esac
          done
          echo "$run" | jq '{status, result, publication}'
          echo "### Exécution 101Maintain : $status" >> "$GITHUB_STEP_SUMMARY"
          [ "$status" = "prepared" ]
```

L'identifiant `github.run_id` rend la demande idempotente si le job est relancé. Un `409` avec `existingRun` est traité comme un succès : le workflow suit l'exécution déjà en cours.

> [!TIP]
> Pour un audit planifié, remplacez le déclencheur par `schedule` (par exemple `cron: '0 6 * * 1'`), la route par `POST …/audits` et l'`Idempotency-Key` par `audit-$(date -u +%G-W%V)`.

## Consommation d'un projet

Droit : Lire la consommation. Les compteurs sont des chaînes décimales ; `cost: null` signifie coût inconnu, jamais gratuit. Voir [Comprendre la consommation](../05-rapports-usage-et-couts/03-comprendre-la-consommation.md).

```bash
curl -sS "$MAINTAIN_URL/api/v1/projects/<projectId>/usage?from=2026-11-01T00:00:00Z&to=2026-12-01T00:00:00Z" \
  -H "Authorization: Bearer $MAINTAIN_API_KEY" | jq '{counters, knownCosts, next}'
```

Filtres disponibles : `kind` (`live` ou `evaluation`), `repository`, `model`, `pull`. La période vaut 30 jours par défaut et 366 jours au plus.

## Pour continuer

Confiez l'intégration à un agent : [Ressources pour agents IA](07-agent-ia.md).
