python-gitlab
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
- breaking python-gitlab v7.0.0 and later require Python 3.10 or higher. Python 3.9 and older are no longer supported.
- breaking In python-gitlab v8.0.0, the GraphQL API client's `GraphQL.execute()` method no longer accepts `graphql.Source` objects directly.
- gotcha Password-based authentication (username/password) is deprecated and largely removed from GitLab API v10.2 onwards. It is highly recommended to use Personal Access Tokens or OAuth tokens.
- gotcha If your GitLab instance redirects HTTP requests to HTTPS (e.g., `http://gitlab.example.com` to `https://gitlab.example.com`), you must specify the final HTTPS URL in the `Gitlab` object constructor to avoid `RedirectionError` or malformed requests.
- gotcha By default, python-gitlab handles rate limiting by sleeping and retrying based on `Retry-After` headers or exponential backoff. It also does *not* retry transient HTTP errors (5xx codes) by default.
Install
-
pip install python-gitlab
Imports
- Gitlab
import gitlab gl = gitlab.Gitlab(...)
Quickstart
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}")