search
LoginSignup
1

posted at

updated at

Python3: GitLab API の使い方

トークンとプロジェクトID の設定

.env
PERSONAL_ACCESS_TOKEN=glpat-xxxxxx
PROJECT_ID="35195199"

プロジェクトのメンバーの取得

get_members.py
#! /usr/bin/python
#
#	get_members.py
#
#					May/06/2022
# ------------------------------------------------------------------
import  os
import  sys
import  json
import  requests
from dotenv import load_dotenv
# ------------------------------------------------------------------
dotenv_path = '.env'
load_dotenv(dotenv_path)
token = os.environ.get("PERSONAL_ACCESS_TOKEN")
project_id = os.environ.get("PROJECT_ID")
#
limit="?page=1&per_page=10"
url="https://gitlab.com/api/v4/projects/" + project_id + "/members" + limit
#
sys.stderr.write("*** 開始 ***\n")
#
headers = {"Content-Type": "application/json",
	"PRIVATE-TOKEN": token}

rr=requests.get(url, headers=headers)
#
json_str = rr.text
dict_aa = json.loads(json_str)
print(len(dict_aa))
#
for unit_aa in dict_aa:
	str_out = str(unit_aa['id']) + "\t" + unit_aa['username'] + "\t"
	str_out += unit_aa['name'] + "\t"
	str_out += unit_aa['web_url']  + "\t"
	str_out += unit_aa['created_at']
	print(str_out)
#
sys.stderr.write("*** 終了 ***\n")
# ------------------------------------------------------------------

プロジェクトのブランチの取得

get_branches.py
#! /usr/bin/python
#
#	get_branches.py
#
#					May/06/2022
# ------------------------------------------------------------------
import  os
import  sys
import  json
import  requests
from dotenv import load_dotenv
# ------------------------------------------------------------------
dotenv_path = '.env'
load_dotenv(dotenv_path)
token = os.environ.get("PERSONAL_ACCESS_TOKEN")
project_id = os.environ.get("PROJECT_ID")
#
limit="?page=1&per_page=10"
url="https://gitlab.com/api/v4/projects/" + project_id + "/repository/branches" + limit
#
sys.stderr.write("*** 開始 ***\n")
#
headers = {"Content-Type": "application/json",
	"PRIVATE-TOKEN": token}

rr=requests.get(url, headers=headers)
#
json_str = rr.text
dict_aa = json.loads(json_str)
print(len(dict_aa))
#
for unit_aa in dict_aa:
	str_out = unit_aa['name'] + "\t"
	str_out += str(unit_aa['merged'])  + "\t"
	str_out += unit_aa['commit']['author_name']  + "\t"
	str_out += unit_aa['commit']['created_at']
	print(str_out)
#
sys.stderr.write("*** 終了 ***\n")
# ------------------------------------------------------------------

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
1