Search code examples
pythongitlab-ci

How do I pass variables to GitLab CI Pipeline API using Python Requests?


I want to pass a variable from Python script to a GitLab CI Pipeline API.

Example

response = requests.post("https://gitlab.com/api/v4/projects/{project_id}/trigger/pipeline", 
                         data={'token': 'token', 'ref': 'branch', 'variables': [{'key': 'MR_ID', 'value': 'VALUE'}])

response = requests.post("https://gitlab.com/api/v4/projects/{project_id}/trigger/pipeline", 
                         data={'token': 'token', 'ref': 'branch', {variables': [{'key': 'MR_ID', 'value': 'VALUE'}]})

Unfortunately this returns a HTTP 400 with the text {"error":"variables is invalid"}. What am I doing wrong?

Documentation


Solution

  • Looks like you misunderstand what the data parameter is in a requests.post. If you have a look at the docs you can see, that the information from data will be delivered in the body.

    What you want to fulfill the gitlab API is the params parameter of requests.

    params will encode the data in the URL as query parameter like this:

    requests.post("https://gitlab.example.com/api/v4/projects/YOUR_PROJECT_ID/pipeline", params={"MR_ID": "VALUE"});
    

    So you have to put your variables in the params parameter and the other information you have in data at the right place (like token in the header etc.)