The python wrapper for the GitLab REST and GraphQL APIs.
—
Core client configuration, authentication methods, server connectivity, and session management for the GitLab API. The Gitlab client serves as the main entry point for all API interactions and provides flexible authentication options.
The main Gitlab client class that manages server connections, authentication, and API access. Supports multiple authentication methods and extensive configuration options.
class Gitlab:
def __init__(
self,
url: str | None = None,
private_token: str | None = None,
oauth_token: str | None = None,
job_token: str | None = None,
ssl_verify: bool | str = True,
http_username: str | None = None,
http_password: str | None = None,
timeout: float | None = None,
api_version: str = "4",
per_page: int | None = None,
pagination: str | None = None,
order_by: str | None = None,
user_agent: str = "python-gitlab/6.3.0",
retry_transient_errors: bool = False,
keep_base_url: bool = False,
**kwargs
) -> None:
"""
Initialize GitLab client with connection and authentication parameters.
Parameters:
- url: The URL of the GitLab server (defaults to https://gitlab.com)
- private_token: User private token for authentication
- oauth_token: OAuth token for authentication
- job_token: CI job token for authentication
- ssl_verify: Whether to verify SSL certificates (bool) or path to CA file (str)
- http_username: Username for HTTP basic authentication
- http_password: Password for HTTP basic authentication
- timeout: Request timeout in seconds
- api_version: GitLab API version to use (only "4" supported)
- per_page: Default number of items per page for pagination
- pagination: Pagination method ("keyset" for keyset pagination)
- order_by: Default ordering for list operations
- user_agent: Custom user agent string
- retry_transient_errors: Whether to retry on 5xx errors
- keep_base_url: Keep user-provided base URL for pagination
"""@classmethod
def from_config(
cls,
gitlab_id: str = "global",
config_files: list[str] | None = None
) -> Gitlab:
"""
Create Gitlab instance from configuration file.
Parameters:
- gitlab_id: Configuration section name (default: "global")
- config_files: List of configuration file paths
Returns:
Configured Gitlab instance
"""Usage example:
# From default config file locations
gl = gitlab.Gitlab.from_config()
# From specific config file and section
gl = gitlab.Gitlab.from_config("my-gitlab", ["/path/to/config.cfg"])def auth(self) -> CurrentUser:
"""
Authenticate with GitLab and return current user.
Returns:
CurrentUser object representing the authenticated user
Raises:
GitlabAuthenticationError: If authentication fails
"""
def version(self) -> dict:
"""
Get GitLab server version information.
Returns:
Dictionary with version, revision, and other server details
"""Usage examples:
import gitlab
# Authenticate with private token
gl = gitlab.Gitlab("https://gitlab.example.com", private_token="glpat-xxxx")
user = gl.auth()
print(f"Logged in as: {user.name} ({user.username})")
# Check server version
version_info = gl.version()
print(f"GitLab version: {version_info['version']}")Low-level HTTP methods for direct API access when higher-level methods don't suffice.
def http_get(
self,
path: str,
query_data: dict | None = None,
streamed: bool = False,
raw: bool = False,
**kwargs
) -> Any:
"""
Perform HTTP GET request.
Parameters:
- path: API endpoint path
- query_data: Query parameters dictionary
- streamed: Whether to return streaming response
- raw: Whether to return raw response object
Returns:
Response data (dict/list/bytes depending on content type)
"""
def http_post(
self,
path: str,
post_data: dict | None = None,
raw: bool = False,
files: dict | None = None,
**kwargs
) -> Any:
"""
Perform HTTP POST request.
Parameters:
- path: API endpoint path
- post_data: Request body data
- raw: Whether to return raw response object
- files: Files to upload
Returns:
Response data
"""
def http_put(
self,
path: str,
put_data: dict | None = None,
raw: bool = False,
files: dict | None = None,
**kwargs
) -> Any:
"""Perform HTTP PUT request."""
def http_patch(
self,
path: str,
patch_data: dict | None = None,
raw: bool = False,
files: dict | None = None,
**kwargs
) -> Any:
"""Perform HTTP PATCH request."""
def http_delete(self, path: str, **kwargs) -> Any:
"""Perform HTTP DELETE request."""
def http_head(self, path: str, **kwargs) -> Any:
"""Perform HTTP HEAD request."""
def http_list(
self,
path: str,
query_data: dict | None = None,
**kwargs
) -> GitlabList:
"""
Perform HTTP GET request returning paginated list.
Returns:
GitlabList object with pagination support
"""def search(
self,
scope: str,
search: str,
**kwargs
) -> list[dict]:
"""
Perform global search across GitLab instance.
Parameters:
- scope: Search scope ("projects", "issues", "merge_requests", "milestones", "snippet_titles", "users")
- search: Search query string
Returns:
List of search results
"""
def markdown(
self,
text: str,
project: str | None = None,
gfm: bool = False
) -> dict:
"""
Render Markdown text using GitLab's Markdown processor.
Parameters:
- text: Markdown text to render
- project: Project context for rendering (for project-specific references)
- gfm: Whether to use GitHub Flavored Markdown
Returns:
Dictionary with rendered HTML
"""
def get_license(self) -> dict:
"""Get GitLab license information (GitLab EE only)."""
def set_license(self, license: str) -> dict:
"""Set GitLab license (GitLab EE only)."""class GitlabConfigParser:
def __init__(self, config_files: list[str] | None = None) -> None:
"""
Initialize configuration parser.
Parameters:
- config_files: List of configuration file paths to read
"""
def get_gitlab_config(self, gitlab_id: str = "global") -> dict:
"""
Get configuration for specific GitLab instance.
Parameters:
- gitlab_id: Configuration section name
Returns:
Dictionary with configuration parameters
"""Example configuration file (~/.python-gitlab.cfg):
[global]
default = local
ssl_verify = true
timeout = 60
[local]
url = https://gitlab.example.com
private_token = glpat-xxxxxxxxxxxxxxxxxxxx
api_version = 4
[gitlab-com]
url = https://gitlab.com
private_token = glpat-yyyyyyyyyyyyyyyyyyyyclass PrivateTokenAuth:
"""Private token authentication backend."""
def __init__(self, token: str) -> None: ...
class OAuthTokenAuth:
"""OAuth token authentication backend."""
def __init__(self, token: str) -> None: ...
class JobTokenAuth:
"""CI job token authentication backend."""
def __init__(self, token: str) -> None: ...class GitlabAuthenticationError(GitlabError):
"""Raised when authentication fails."""
pass
class GitlabConnectionError(GitlabError):
"""Raised when connection to GitLab server fails."""
pass
class GitlabHttpError(GitlabError):
"""Raised for HTTP-level errors."""
passExample error handling:
try:
gl = gitlab.Gitlab("https://gitlab.example.com", private_token="invalid")
user = gl.auth()
except gitlab.GitlabAuthenticationError:
print("Invalid authentication credentials")
except gitlab.GitlabConnectionError:
print("Unable to connect to GitLab server")
except gitlab.GitlabHttpError as e:
print(f"HTTP error {e.response_code}: {e.error_message}")@property
def user(self) -> CurrentUser | None:
"""Get currently authenticated user (if authenticated)."""
@property
def server_version(self) -> str | None:
"""Get GitLab server version string."""
@property
def server_revision(self) -> str | None:
"""Get GitLab server revision hash."""
@property
def api_url(self) -> str:
"""Get full API URL."""
@property
def api_version(self) -> str:
"""Get API version being used."""The Gitlab client provides direct access to all resource managers:
# Project and repository managers
@property
def projects(self) -> ProjectManager: ...
@property
def groups(self) -> GroupManager: ...
@property
def users(self) -> UserManager: ...
# Administrative managers
@property
def runners(self) -> RunnerManager: ...
@property
def settings(self) -> ApplicationSettingsManager: ...
@property
def features(self) -> FeatureManager: ...
# And 100+ more resource managers...This provides convenient access to all GitLab resources:
gl = gitlab.Gitlab(url, token)
# Access projects
projects = gl.projects.list()
# Access users
users = gl.users.list()
# Access runners
runners = gl.runners.list()Install with Tessl CLI
npx tessl i tessl/pypi-python-gitlab