通过 API 触发 GitHub Actions | AI生成和翻译

Home 2026.02

Question: 如何通过 API 触发 GitHub Actions workflow?

Answer:

通过 GitHub REST API 触发 GitHub Actions workflow 主要有两种方式:

  1. 使用 workflow_dispatch — 推荐用于手动触发特定的 workflow(最常见的使用场景)。 workflow 必须包含 on: workflow_dispatch:(可选择性配置 inputs)。

  2. 使用 repository_dispatch — 用于从外部系统通过自定义事件类型触发 workflow(适用于跨仓库或第三方集成)。

1. 通过 workflow_dispatch 触发(首选方法)

Workflow 文件要求 (.github/workflows/my-workflow.yml):

on:
  workflow_dispatch:
    inputs:
      environment:
        description: 'Environment to deploy to'
        required: true
        default: 'staging'
      version:
        description: 'Version tag'
        required: false

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - run: echo "Deploying to $ version $"

API Endpoint

POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches

Example using curl (2022-11-28 API 版本 — 截至 2026 年的当前版本):

curl -L \
  -X POST \
  -H "Accept: application/vnd.github+json" \
  -H "Authorization: Bearer YOUR_PERSONAL_ACCESS_TOKEN" \
  -H "X-GitHub-Api-Version: 2022-11-28" \
  https://api.github.com/repos/OWNER/REPO/actions/workflows/deploy.yml/dispatches \
  -d '{
    "ref": "main",
    "inputs": {
      "environment": "production",
      "version": "v1.5.0"
    }
  }'

Using GitHub CLI(更简单):

gh workflow run deploy.yml \
  --ref main \
  -f environment=production \
  -f version=v1.5.0

2. 通过 repository_dispatch 触发(自定义事件)

Workflow 文件要求

on:
  repository_dispatch:
    types: [deploy, build, test]

API Endpoint

POST /repos/{owner}/{repo}/dispatches

Example curl:

curl -L \
  -X POST \
  -H "Accept: application/vnd.github+json" \
  -H "Authorization: Bearer YOUR_PERSONAL_ACCESS_TOKEN" \
  -H "X-GitHub-Api-Version: 2022-11-28" \
  https://api.github.com/repos/OWNER/REPO/dispatches \
  -d '{
    "event_type": "deploy",
    "client_payload": {
      "environment": "prod",
      "service": "api"
    }
  }'

在 workflow 中你可以通过以下方式访问:

github.event.client_payload.environment

Authentication & Permissions

Quick Tips

References:


Back Donate