How to use GitLab API within CI

Query information via the GitLab API from within the GitLab CI

You can request information from a GitLab repository by API from the command line, which have the following layout:

curl --header "token=<TOKEN>" "<PROJECT_API_URL>/<REQUEST_SPECIFICS>"

Here, ‘TOKEN’ is an access token. For instance, you can create a personal token (see here) within your user profile settings. When a job is started within the GitLab CI , the variable ‘CI_JOB_TOKEN’ is available. However, with this token you have limited privileges (see this readme). Therefore, you can create a project token (see here), which you can then use in your .gitlab-ci.yml file.

For instance, you can then query information on recently run pipelines , a specific pipeline or a specific commit :

# information on recently run pipelines
curl --header "token=<TOKEN>" "<PROJECT_API_URL>/pipelines"

# information on a specific pipeline with the id 'ID'
curl --header "token=<TOKEN>" "<PROJECT_API_URL>/pipelines/<ID>"

# information on a particular commit with the SHA 'SHA'
curl --header "token=<TOKEN>" "<PROJECT_API_URL>/repository/commits/<SHA>"

The information is returned in the form of json dictionaries with fields as ‘last_pipeline’ e.g. This way you can check if a pipeline has already started or succeeded for a specific commit.

See also