Fetching data from GitLab's API using API key

Fetch API cURL API key GitLab JS PHP

Continuing the data structures, in this article I will write about graphs. These structures can be used in a big variety of applications. For implementation I will use an adjacency list approach, but in the introduction I also talk about the adjacency matrix version. Apart from the implementation I write (and talk) about the theory and real life usages of graphs.


API access

Most modern big software companies provide some kind of API access to their services – fortunately GitLab is also following this approach. Based on this we can create third party applications which use these APIs.

In this article we will write a simple program which uses GitLab’s TODO API. In short you can create to do tasks in GitLab, based on the issues we have in the code. We could create a third party app which calls the GitLab API when we finished a task and marking the given TODO as done. In a previous article I wrote about how to create a basic PHP API endpoint and returning our own JSON data.

Generating API key on GitLab

Most (all?) platforms need some security filters and for this reason an API KEY based authentication is a good habit. For this on GitLab we have to request an API key – which is called Personal Access Token (PAT) in GitLab.

Steps for GitLab PAT request:

  • Log in to GitLab.
  • In the upper-right corner, click your avatar and select Settings.
  • On the User Settings menu, select Access Tokens.
  • Choose a name and optional expiry date for the token.
  • Choose the desired scopes.
  • Click the Create personal access token button.
  • Save the personal access token somewhere safe. Once you leave or refresh the page, you won’t be able to access it again.

Development

After having the PAT, we can create the web app to fetch the data. For this, we will create two scenarios: PHP and JS. In PHP we will use cURL library to get the data from the API and display the full in the browser. In the JS version we will write out to the console only a few selected properties.

Using CURL from CLI

From the command line we can easily test if the API token is correct, by executing the command below, with the these instructions:

  • "PRIVATE-TOKEN:"
    • make sure you do not change this name; other API-s use different names (eg. “API-KEY:” or something else) but GitLab uses “PRIVATE-TOKEN:”
  • <your_access_token>
    • here we have to paste our token which we requested through GitLab previously
  • --header
    • is important to be set, otherwise we will get “unauthorized” error
  • https://gitlab.example.com/api/v4/todos
    • adjust this URL according to yours
    • my personal URL look like this https://gitlab.com/api/v4/todos, since I’m using the “gitlab itself”, not hosting it somewhere
1
curl --header "PRIVATE-TOKEN: <your_access_token>" https://gitlab.example.com/api/v4/todos

Running this command – make sure curl is installed – we should get an output where all the JSON response data displayed in raw form.

Coding the PHP client

In PHP we will use cURL as well to get the data. The code below shows the full .php file, but note that your API key must be inserted. Note that as mentioned above, the “PRIVATE-TOKEN:” string is also used here. After the code is run from any localhost or live server, the JSON output should be visible. If we set the header (we did below), we can use some JSON formatter plugin to pretty-print the data.

1
2
3
4
5
6
7
8
9
10
11
<?php
    $my_token = "<_YOUR_API_KEY_>"; // add your requested API key here

    $url = "https://gitlab.com/api/v4/todos";
    $handle = curl_init();
    curl_setopt($handle, CURLOPT_URL, $url);
    curl_setopt($handle, CURLOPT_HTTPHEADER, array('PRIVATE-TOKEN: ' . $my_token));
    header('Content-Type: application/json');
    curl_exec($handle);
    curl_close($handle);
?>

Coding the JS client

The same feature can be done from plain JavaScript, using XMLHttpRequest. Everything remained the same, except that we can directly get the response object, parse it and write out the needed properties. At the time of writing this, there were two to do records in my GitLab for testing so I wrote out the id of them, their title and the link to them on GitLab.

Note that XMLHttpRequest is not the newest approach, so if we want to be a bit more up-to-date we should use the Fetch API instead. Both of them can be found below but I recommend using the fetch version.

Using XMLHttpRequest (deprecated approach)

1
2
3
4
5
6
7
8
9
10
11
12
13
var request = new XMLHttpRequest()
request.open('GET', 'https://gitlab.com/api/v4/todos', true)
request.setRequestHeader("PRIVATE-TOKEN","<_YOUR_API_KEY_>")
request.onload = function() {
    var data = JSON.parse(this.response)
    data.forEach(x => {
        console.log(x.id)
        console.log(x.target.title)
        console.log(x.target.web_url)
        console.log("")
    })
}
request.send()

Using Fetch API (modern approach)

1
2
3
4
5
6
7
8
9
10
11
12
13
var request = new XMLHttpRequest()
request.open('GET', 'https://gitlab.com/api/v4/todos', true)
request.setRequestHeader("PRIVATE-TOKEN","<_YOUR_API_KEY_>")
request.onload = function() {
    var data = JSON.parse(this.response)
    data.forEach(x => {
        console.log(x.id)
        console.log(x.target.title)
        console.log(x.target.web_url)
        console.log("")
    })
}
request.send()

Console output

1
2
3
4
5
6
7
59845738
This is a second test issue for the api example
https://gitlab.com/siposm/siposm.hu/-/issues/2

59841879
TEST ISSUE FOR API
https://gitlab.com/siposm/siposm.hu/-/issues/1

End result

We successfully used GitLab’s API to fetch real-life data. This can be used for some workflow management software where you want to display all the currently pending tasks in the to do list. You can mark tasks as done also by using the API a bit more differently – sending POST instead of GET. This also can be helpful if you want to automate some processes but you don’t want to (or not able to) click through the GUI of the website…

The full codes can be downloaded from my GitLab group. Look for the “gitlab-todo-api” repository.