python-gitlab

8.2.0 · active · verified Sun Mar 29

python-gitlab is a Python package that provides a comprehensive wrapper for the GitLab REST and GraphQL APIs. It allows developers to interact with GitLab resources in a Pythonic way, offering both synchronous and asynchronous clients, along with a CLI tool. The library maintains a regular release cadence, typically releasing new versions monthly, ensuring up-to-date support for GitLab API features.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to connect to a GitLab instance using a personal access token and then fetch a list of projects owned by the authenticated user. It highlights setting the GitLab URL and private token via environment variables for security and explicitly uses API v4.

import os
import gitlab

# Configure GitLab connection using environment variables
GITLAB_URL = os.environ.get('GITLAB_URL', 'https://gitlab.com')
GITLAB_PRIVATE_TOKEN = os.environ.get('GITLAB_PRIVATE_TOKEN', 'your_private_token_here')

# Initialize the Gitlab API client
# Ensure you use 'https://' if your GitLab instance redirects from http
try:
    gl = gitlab.Gitlab(
        url=GITLAB_URL,
        private_token=GITLAB_PRIVATE_TOKEN,
        api_version='4' # Explicitly set API version, often '4'
    )
    
    # Optional: Validate the token by getting the current authenticated user
    gl.auth() 
    user = gl.user.get()
    print(f"Connected to GitLab as: {user.username}")

    # List current user's projects
    print("\nListing your projects:")
    projects = gl.projects.list(owned=True, all=True)
    if projects:
        for project in projects:
            print(f"  - {project.name} (ID: {project.id})")
    else:
        print("  No projects found.")

except gitlab.exceptions.GitlabError as e:
    print(f"GitLab API error: {e}")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

view raw JSON →