# Publish from GitHub

> Let GitHub Actions check every pull request and publish every merge — the repository proves itself with the token GitHub signs for each workflow run, and one key tries the deployment.

An application whose code lives in a GitHub repository can be checked and published by GitHub
Actions: each pull request creates a version and checks it, and each push to the production branch
deploys it, calls one of its actions, then puts it in production. Every workflow run proves where it comes
from with the identity token GitHub signs for it; the one secret it keeps is your application's key, with
which it tries the deployment at your `--staging` address.

Most applications never need this: an assistant with the MCP tools writes, tries and publishes a
version itself. It suits an application several people change through pull requests.

## Set it up

Three steps; an assistant does the first two, a member of your team the third.

1. **Link the repository to the application.** With the MCP tools, `app_settings` with the
   application's `app_id` and `github_repository: "owner/name"`; add `github_branch` when the
   production branch is not `main`. Only the workflow runs of one file count, `.github/workflows/apigami.yml`
   unless `github_workflow` names another. Several applications may link the same repository, one folder
   and one workflow file each, such as `.github/workflows/apigami-crm.yml`.
2. **Add the workflow file.** Save it under the name the link expects and fill its `env` block:

   ```sh
   mkdir -p .github/workflows
   curl -fsSL https://www.apigami.com/github/apigami.yml -o .github/workflows/apigami.yml
   ```

   - `APIGAMI_APP_ID`: the application, from `app_list`.
   - `APIGAMI_APP_DIR`: the folder holding its `manifest.json`, relative to the repository's root;
     `.` when it is the root.
   - `APIGAMI_CHECK_ACTION`: the `operationId` of an action that writes nothing and needs no browser,
     such as a health check. A version is published only once one of its actions answered on its own
     deployment, and this is the one the workflow runs.

   Change `branches: [main]` under `push` when the production branch has another name, and add a
   `paths` filter there and under `pull_request`, such as `paths: ['crm/**']`, when the repository
   holds several applications. The workflow sends the files git tracks in `APIGAMI_APP_DIR`, nothing
   else. Commit the file: the next pull request runs it.

   The workflow builds nothing. A project whose [pages are built by Vite](/docs/app-server/#pages-built-by-vite)
   is sent as its sources, `dist/` and `node_modules/` left out of git, and Apigami builds it when the version
   is deployed: a build that fails stops the push's workflow run with its reason, not the pull request's check.
3. **Give the workflow your application's key.** `app_keys_write` creates one and shows it once; a member
   pastes it into the repository's secrets as `APIGAMI_KEY` (Settings, Secrets and variables, Actions). The key
   acts for every person connected to your application: keep it there only, and revoke it with
   `app_keys_write` if it leaks. A pull request never receives it. When the repository holds several
   applications, each key takes its own secret name, such as `APIGAMI_KEY_CRM`, and the line
   `APIGAMI_KEY: ${{ secrets.APIGAMI_KEY }}` of that application's file reads that name.

The workflow runs act as the member who linked the repository, while they are in the team. `app_status`
shows the link; `app_settings` with `github_repository: null` removes it, and the workflow runs are refused
from then on.

## What each workflow run does

| Step | Pull request | Push to the production branch |
|---|---|---|
| Send the folder as a new version, built on the one in production | yes | yes |
| Fail on what the validation found, and on a variable without a value | yes | yes |
| Show which files changed against production | yes | yes |
| Deploy it | — | yes |
| Call `APIGAMI_CHECK_ACTION` on that deployment, at the `--staging` address | — | yes |
| Put it in production | — | yes |

A variable the manifest requires and that holds no value fails the check with a link where a member
types it. That page stays open an hour; running the job again gives a new one. An assistant can also ask for
it with `app_environment_write`, before the version that declares the variable exists.

An application that is `public` is not put in production at once: the version waits for
[Apigami's review](/docs/app-publish/#run-it-deploy-it-publish-it), and the workflow run ends green with a note.

A pull request coming from a fork receives no identity token from GitHub, so its check sends nothing
and says so.

## How a run proves itself

The workflow asks GitHub for an OpenID Connect token whose audience is `https://api.eu.apigami.com`
(`permissions: id-token: write`), a fresh one before each call, and sends it as the `Bearer`. Apigami
checks GitHub's signature, finds the application linked to the repository the token names, checks that
the workflow run comes from the file the link names, and allows:

- to any workflow run of that repository: reading versions, creating one, and asking for the page where a
  member types a missing variable's value;
- to a `push` or a manual workflow run on the production branch only: deploying and publishing.

Nothing else: not another application, not `/mcp`, not a browser, not the team, and not an action at an
address, which takes the key. The first workflow run records
the repository's numeric id, so a repository deleted and created again under the same name is refused
until a member links it again.

## The workflow file

```yaml title=".github/workflows/apigami.yml"
# Apigami: each pull request creates and checks a version of the application; each push to the
# production branch deploys it, calls its check action at the --staging address and puts it in production.
# GitHub signs a token for every run; the secret APIGAMI_KEY calls the action. https://www.apigami.com/docs/app-github/
name: Apigami

on:
  pull_request:
  push:
    branches: [main]
  workflow_dispatch:

permissions:
  contents: read
  id-token: write

concurrency:
  group: apigami-${{ github.ref }}
  cancel-in-progress: false

env:
  APIGAMI_APP_ID: ""          # the application, from app_list
  APIGAMI_APP_DIR: "."        # the folder holding manifest.json, from the repository's root
  APIGAMI_CHECK_ACTION: ""    # the operationId of an action that writes nothing, called on the deployment before production
  APIGAMI_API: https://api.eu.apigami.com

jobs:
  apigami:
    runs-on: ubuntu-latest
    timeout-minutes: 30
    env:
      IS_FORK: ${{ github.event.pull_request.head.repo.full_name != '' && github.event.pull_request.head.repo.full_name != github.repository }}
    steps:
      - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0

      - name: Send and check the version
        id: version
        run: |
          set -euo pipefail
          if [ -z "${ACTIONS_ID_TOKEN_REQUEST_URL:-}" ]; then
            if [ "$IS_FORK" = true ]; then
              echo "::notice::GitHub gives no identity token to a pull request from a fork: nothing was sent to Apigami."
              echo "skipped=true" >> "$GITHUB_OUTPUT"
              exit 0
            fi
            echo "::error::GitHub gave this run no identity token: add permissions: id-token: write to the workflow."; exit 1
          fi
          [ -n "$APIGAMI_APP_ID" ] || { echo "::error::Set APIGAMI_APP_ID in .github/workflows/apigami.yml"; exit 1; }

          token() {
            curl -sSf -H "Authorization: Bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" \
              "$ACTIONS_ID_TOKEN_REQUEST_URL&audience=$APIGAMI_API" | jq -r .value
          }
          # api METHOD PATH [curl options]: prints the answer, fails on a status from 400 with Apigami's sentence.
          api() {
            local method=$1 path=$2 body status
            shift 2
            body=$(mktemp)
            status=$(curl -sS -o "$body" -w '%{http_code}' -X "$method" "$APIGAMI_API$path" \
              -H "Authorization: Bearer $(token)" "$@")
            if [ "$status" = 000 ] || [ "$status" -ge 400 ]; then
              echo "::error::$method $path answered $status: $(jq -r '.error // .' "$body" 2>/dev/null || cat "$body")" >&2
              return 1
            fi
            cat "$body"
          }
          APP="/v1/apps/$APIGAMI_APP_ID"

          # The new version is built on production's, which publishing requires: read pages until it shows.
          PRODUCTION=""
          for OFFSET in 0 100 200 300 400 500; do
            PAGE=$(api GET "$APP/versions?offset=$OFFSET")
            PRODUCTION=$(jq -r '[.versions[] | select(.production)][0].version_id // empty' <<<"$PAGE")
            [ -n "$PRODUCTION" ] || [ "$(jq '.versions | length' <<<"$PAGE")" -lt 100 ] && break
          done
          RESERVED=$(api POST "$APP/versions" -H 'Content-Type: application/json' \
            -d "$(jq -n --arg base "$PRODUCTION" '{mode: "archive", base_version_id: (if $base == "" then null else $base end)}')")
          VERSION=$(jq -r .version_id <<<"$RESERVED")

          TREE=HEAD
          [ "$APIGAMI_APP_DIR" = "." ] || TREE="HEAD:${APIGAMI_APP_DIR#./}"
          UPLOADED=$(mktemp)
          STATUS=$(git archive --format=zip "$TREE" | curl -sS -o "$UPLOADED" -w '%{http_code}' -X PUT \
            "$(jq -r .upload.url <<<"$RESERVED")" -H 'Content-Type: application/zip' --data-binary @-)
          if [ "$STATUS" -ge 400 ]; then
            echo "::error::The upload answered $STATUS: $(jq -r '.error // .' "$UPLOADED")"; exit 1
          fi
          echo "version_id=$VERSION" >> "$GITHUB_OUTPUT"

          if [ "$(jq -r .validation.status "$UPLOADED")" != "valid" ]; then
            jq -r '.validation.diagnostics[] | "::error file=\(.file // "manifest.json")::\(.message)"' "$UPLOADED"
            echo "::error::Version $VERSION is not valid: fix what is listed above."
            exit 1
          fi

          MISSING=$(api GET "$APP/versions/$VERSION" | jq -c '.missing_variables')
          if [ "$MISSING" = null ]; then
            echo "::error::Apigami could not read the application's variables this time: run the job again."; exit 1
          fi
          if [ "$MISSING" != "[]" ]; then
            LINK=$(api POST "$APP/environment/confirmations" -H 'Content-Type: application/json' \
              -d "{\"names\": $MISSING}" | jq -r .confirmation_url)
            echo "::error::No value yet for $(jq -r 'join(", ")' <<<"$MISSING"). A member types it at $LINK (for one hour; running this job again gives a new link), or asks their assistant."
            exit 1
          fi

          {
            echo "### Apigami: version $VERSION is valid"
            if [ -n "$PRODUCTION" ]; then
              api GET "$APP/versions/$VERSION?base_version_id=$PRODUCTION" \
                | jq -r '.diff.counts | "Against production: \(.changed) changed, \(.added) added, \(.removed) removed files."'
            else
              echo "Nothing is in production yet."
            fi
          } >> "$GITHUB_STEP_SUMMARY"

      - name: Deploy, check and publish
        if: github.event_name != 'pull_request' && steps.version.outputs.skipped != 'true'
        env:
          VERSION: ${{ steps.version.outputs.version_id }}
          APIGAMI_KEY: ${{ secrets.APIGAMI_KEY }}
        run: |
          set -euo pipefail
          [ -n "$APIGAMI_CHECK_ACTION" ] || { echo "::error::Set APIGAMI_CHECK_ACTION in .github/workflows/apigami.yml: a version is published only once one of its actions answered on its deployment."; exit 1; }
          [ -n "$APIGAMI_KEY" ] || { echo "::error::Add the repository secret APIGAMI_KEY, a key of the application from app_keys_write: the check action is called with it."; exit 1; }
          # The check action's method and path, from the manifest: it is called at the address, never by name.
          read -r CHECK_METHOD CHECK_PATH < <(jq -r --arg op "$APIGAMI_CHECK_ACTION" \
            '.paths | to_entries[] | .key as $path | .value | to_entries[] | select(.value.operationId? == $op) | "\(.key | ascii_upcase) \($path)"' \
            "$APIGAMI_APP_DIR/manifest.json" | head -n 1) || true
          [ -n "${CHECK_PATH:-}" ] || { echo "::error::No operation of manifest.json has the operationId $APIGAMI_CHECK_ACTION."; exit 1; }
          case "$CHECK_PATH" in *"{"*) echo "::error::$APIGAMI_CHECK_ACTION is served at a path template: choose a check action with a literal path."; exit 1;; esac
          token() {
            curl -sSf -H "Authorization: Bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" \
              "$ACTIONS_ID_TOKEN_REQUEST_URL&audience=$APIGAMI_API" | jq -r .value
          }
          call() {
            local method=$1 path=$2
            shift 2
            curl -sS -o answer.json -D headers.txt -w '%{http_code}' --max-time 900 -X "$method" "$APIGAMI_API$path" \
              -H "Authorization: Bearer $(token)" "$@" || true
          }
          APP="/v1/apps/$APIGAMI_APP_ID"

          STATUS=$(call PATCH "$APP/versions/$VERSION" -H 'Content-Type: application/json' -d '{"deployed":true}')
          if [ "$STATUS" -ge 500 ] || [ "$STATUS" = 000 ]; then
            # The deployment goes on without the connection: wait for it.
            for _ in $(seq 90); do
              sleep 10
              STATUS=$(call GET "$APP/versions/$VERSION")
              [ "$STATUS" = 200 ] && [ "$(jq -r '.deployed or (.error != null)' answer.json)" = true ] && break
            done
          fi
          if [ "$STATUS" -ge 400 ] || [ "$(jq -r .deployed answer.json)" != true ]; then
            echo "::error::Deploying version $VERSION failed: $(jq -r '.error // .' answer.json)"; exit 1
          fi

          # The version just deployed answers at the --staging address, to the application's key.
          STAGING=$(jq -r '.address.staging // empty' answer.json)
          [ -n "$STAGING" ] || { echo "::error::Version $VERSION has no --staging address."; exit 1; }
          BODY=(); [ "$CHECK_METHOD" = GET ] || [ "$CHECK_METHOD" = HEAD ] || BODY=(-H 'Content-Type: application/json' -d '{}')
          STATUS=$(curl -sS -o answer.json -D headers.txt -w '%{http_code}' --max-time 120 -X "$CHECK_METHOD" \
            "${STAGING%/}$CHECK_PATH" -H "Authorization: Bearer $APIGAMI_KEY" "${BODY[@]}" || true)
          # With X-Apigami-Platform, Apigami refused before any code ran: a revoked key, for instance.
          if grep -qi '^x-apigami-platform:' headers.txt; then
            echo "::error::Apigami refused $APIGAMI_CHECK_ACTION ($STATUS): $(jq -r '.error // .' answer.json)"; exit 1
          fi
          if [ "$STATUS" -ge 500 ] || [ "$STATUS" = 000 ]; then
            echo "::error::$APIGAMI_CHECK_ACTION answered $STATUS on version $VERSION: $(head -c 2000 answer.json)"; exit 1
          fi

          # The answer at --staging reaches Apigami's record a few seconds later: publishing waits for it.
          for _ in $(seq 6); do
            STATUS=$(call PATCH "$APP/versions/$VERSION" -H 'Content-Type: application/json' -d '{"production":true}')
            [ "$STATUS" = 409 ] || break
            sleep 5
          done
          if [ "$STATUS" -ge 400 ]; then
            echo "::error::Publishing version $VERSION answered $STATUS: $(jq -r '.error // .' answer.json)"; exit 1
          fi
          if [ "$(jq -r .review.state answer.json)" = pending_review ]; then
            echo "::notice::Version $VERSION waits for an Apigami administrator's review before it goes in production."
            echo "### Apigami: version $VERSION is waiting for review" >> "$GITHUB_STEP_SUMMARY"
          else
            echo "### Apigami: version $VERSION is in production" >> "$GITHUB_STEP_SUMMARY"
            jq -r '.address // empty' answer.json >> "$GITHUB_STEP_SUMMARY"
          fi
```

## When a workflow run fails

Each failure is one line in the workflow run's annotations, Apigami's own sentence:

- **`… is not linked to this application`**: link the repository with `app_settings`, or check
  `APIGAMI_APP_ID`.
- **`only .github/workflows/apigami.yml of … may act on this application`**: the file has another name;
  set `github_workflow` with `app_settings`, or rename the file.
- **`only a push to main deploys and publishes`**: the production branch of the link is not the one
  that ran; set `github_branch`.
- **`the member who linked this repository is no longer in the application's team`**: another member
  links it again.
- **`GitHub gave this run no identity token`**: the workflow lacks `permissions: id-token: write`.
- **`invalid GitHub Actions token`**: the workflow asks for another audience than
  `https://api.eu.apigami.com`.
- **`Add the repository secret APIGAMI_KEY`**: step 3 of the set-up; **`Apigami refused …`**: the key was
  revoked or is another application's, make a new one.
- **A check action answering `500` or more**, or not answering within two minutes: the version stays
  deployed and out of production. `app_runs` and `app_logs` say why.