githubgithub-actionsgithub-api

How can I trigger a `workflow_dispatch` from the GitHub API?


From the GitHub REST API documentation, it seems we're able to create a repository_dispatch event, but not a workflow_dispatch event. In the GitHub GraphQL API, I couldn't find how to dispatch events.

Is it even possible to trigger a workflow_dispatch event using the API?


Solution

  • Yes, it's possible, manually, through the GitHub API or using the GitHub CLI.

    Manually (through the Actions tab on your repository)

    Here is an official documentation about it.

    Basically, once you select the workflow on the tab, if the workflow implementation has the workflow_dispatch trigger, the option Run workflow will appear on the right part of the window, like this:

    Enter image description here

    With the GitHub API

    In the official GitHub documentation, there is a service to create a workflow dispatch event.

    Here is a curl example:

    curl \
      -X POST \
      -H "Accept: application/vnd.github.v3+json" \
      https://api.github.com/repos/octocat/hello-world/actions/workflows/42/dispatches \
      -d '{"ref":"main"}'
    

    Note that you can also send workflow inputs through this API as well.

    You can also find more references about this in this article.

    There is also another GitHub API service to trigger repository_dispatch events.

    GitHub CLI

    You can also trigger a workflow_dispatch event using the GitHub CLI tool through the command:

    gh workflow run [<workflow-id> | <workflow-name>] [flags]

    Create a workflow_dispatch event for a given workflow.

    This command will trigger GitHub Actions to run a given workflow file. The given workflow file must support a workflow_dispatch 'on' trigger in order to be run in this way.

    Reference.

    Bonus

    If you're looking for triggering those workflow_dispatch events (and repository_dispatch events) through a terminal command line, you can use this automation in Python. The implementation can be found in this class.