I have a python workflow in github here. I can run that workflow from the web interface. But problem is everytime I have to visit github and click on run workflow
. Again I have to login in github from an unknown device to run that workflow. Is there any github module in python that can run a workflow using a personal access token? Or how can I run a workflow with github api using requests module? I searched about this topic on google but I didn’t found any solution that works. Many of those are out dated or not explained properly.
This is the workflow I used here:
name: Python
on:
workflow_dispatch:
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: checkout repo
uses: actions/checkout@v2.3.4
- name: Run a script
run: python3 main.py
Thanks to @C.Nivs & @larsks for helping me to find the right documentation. After experimenting with github api, finally I found my answer. Here is the code I used:
branch, owner, repo, workflow_name, ghp_token="main", "dev-zarir", "Python-Workflow", "python.yml", "ghp_..."
import requests
def run_workflow(branch, owner, repo, workflow_name, ghp_token):
url = f"https://api.github.com/repos/{owner}/{repo}/actions/workflows/{workflow_name}/dispatches"
headers = {
"Accept": "application/vnd.github+json",
"Authorization": f"Bearer {ghp_token}",
"Content-Type": "application/json"
}
data = '{"ref":"'+branch+'"}'
resp = requests.post(url, headers=headers, data=data)
return resp
response=run_workflow(branch, owner, repo, workflow_name, ghp_token)
if response.status_code==204:
print("Workflow Triggered!")
else:
print("Something went wrong.")