This is an old revision of the document!
GitLab provides a powerful API that lets you interact programmatically with a GitLab instance and automate a lot of things.
This tutorial presents how to use the API of GitLab with Python.
For the examples below we will use the instance https://gitlab.example.org. Of course you can use https://gitlab.com.
Get the list of users registered in GitLab
This first example is fairly easy and uses the Users resource.
#! /usr/bin/env python #-*- coding: utf-8 -*- import requests import json # your private token can be found here: # https://gitlab.example.org/profile/account TOKEN = "<your-private-token>" r = requests.get("https://gitlab.example.org/api/v3/users?per_page=100&private_token="+TOKEN) if r.status_code == 200: users = json.loads(r.content) for user in users: print user["username"], user["email"]
Send an email to the members of a GitLab group
Again, this is pretty easy. We will need to use the resource Groups and the resource Users.
In order to send the email, we will use the [[http://www.mutt.org/ | Mutt] email client.
The Mutt command will look like this:
$ mutt -s "The subject" `./get_recipents.py <group-id> /dev/null` < message.txt
As you can see, Mutt needs three parameters:
- the subject of the email. Will be given in parameter;
- the message to be sent. Will be given through a Unix pipeline (message.txt);
- the list of recipients (members of the GitLab group). Will be given in parameter as the result of a Python script.
As you can expect the Python script will use the API of GitLab in order to get the list of recipients. Below you will find a working script:
#! /usr/bin/env python #-*- coding: utf-8 -*- import requests import json # your private token can be found here: # https://gitlab.example.org/profile/account TOKEN = "<your-private-token>" GROUP_ID = 21 EMAILS = [] r = requests.get("https://gitlab.example.org/api/v3/groups/" + str(GROUP_ID) + "/members?private_token=" + TOKEN) if r.status_code == 200: members = json.loads(r.content) for member in members: r = requests.get("https://gitlab.example.org/api/v3/users/" + str(member["id"]) + "?private_token=" + TOKEN) if r.status_code == 200: user = json.loads(r.content) if user["state"] == "active": EMAILS.append(user["email"])
Only active users (user[“state”] == “active”) will receive the email.