The python wrapper for the GitLab REST and GraphQL APIs.
—
Comprehensive project lifecycle management including creation, configuration, access control, and administrative operations. The Project object serves as the central hub for accessing all project-related resources and provides extensive project management capabilities.
The main Project class representing a GitLab project with all associated resources and operations.
class Project(RefreshMixin, SaveMixin, ObjectDeleteMixin, RepositoryMixin, UploadMixin, RESTObject):
"""
GitLab project object with comprehensive resource management.
Key Attributes:
- id: Project ID
- name: Project name
- path: Project path (URL slug)
- path_with_namespace: Full project path including namespace
- description: Project description
- visibility: Project visibility level ("private", "internal", "public")
- default_branch: Default branch name
- web_url: Project web URL
- created_at: Creation timestamp
- updated_at: Last update timestamp
"""
def save(self) -> None:
"""
Save project changes to GitLab server.
Raises:
GitlabUpdateError: If the update fails
"""
def delete(self) -> None:
"""
Delete the project permanently.
Raises:
GitlabDeleteError: If the deletion fails
"""
def refresh(self) -> None:
"""Refresh project data from server."""def star(self) -> None:
"""
Star the project.
Raises:
GitlabCreateError: If starring fails
"""
def unstar(self) -> None:
"""
Unstar the project.
Raises:
GitlabDeleteError: If unstarring fails
"""
def archive(self) -> None:
"""
Archive the project.
Raises:
GitlabCreateError: If archiving fails
"""
def unarchive(self) -> None:
"""
Unarchive the project.
Raises:
GitlabDeleteError: If unarchiving fails
"""
def transfer_project(self, to_namespace: str) -> dict:
"""
Transfer project to another namespace.
Parameters:
- to_namespace: Target namespace name or ID
Returns:
Dictionary with transfer result
Raises:
GitlabTransferProjectError: If transfer fails
"""
def fork(self, namespace: str | None = None, name: str | None = None, path: str | None = None) -> dict:
"""
Fork the project.
Parameters:
- namespace: Target namespace for fork (optional)
- name: Name for forked project (optional)
- path: Path for forked project (optional)
Returns:
Dictionary with fork information
Raises:
GitlabCreateError: If forking fails
"""
def create_fork_relation(self, forked_from_id: int) -> None:
"""
Create fork relationship between projects.
Parameters:
- forked_from_id: ID of the source project
Raises:
GitlabCreateError: If relation creation fails
"""
def delete_fork_relation(self) -> None:
"""
Delete fork relationship.
Raises:
GitlabDeleteError: If relation deletion fails
"""
def languages(self) -> dict[str, float]:
"""
Get programming languages used in project with percentages.
Returns:
Dictionary mapping language names to percentage values
"""
def share(self, group_id: int, group_access: int, expires_at: str | None = None) -> dict:
"""
Share project with a group.
Parameters:
- group_id: ID of group to share with
- group_access: Access level (10=Guest, 20=Reporter, 30=Developer, 40=Maintainer, 50=Owner)
- expires_at: Share expiration date (ISO format, optional)
Returns:
Dictionary with sharing result
"""
def unshare(self, group_id: int) -> None:
"""
Stop sharing project with a group.
Parameters:
- group_id: ID of group to stop sharing with
"""
def housekeeping(self) -> None:
"""
Start housekeeping task for project repository.
Raises:
GitlabHousekeepingError: If housekeeping fails
"""
def snapshot(self, wiki: bool = False) -> dict:
"""
Create project snapshot.
Parameters:
- wiki: Include wiki in snapshot
Returns:
Dictionary with snapshot information
"""class ProjectManager(CRUDMixin[Project]):
"""Manager for GitLab projects with comprehensive filtering and creation options."""
def list(
self,
archived: bool | None = None,
visibility: str | None = None,
order_by: str | None = None,
sort: str | None = None,
search: str | None = None,
search_namespaces: bool | None = None,
simple: bool | None = None,
owned: bool | None = None,
membership: bool | None = None,
starred: bool | None = None,
statistics: bool | None = None,
with_custom_attributes: bool | None = None,
with_issues_enabled: bool | None = None,
with_merge_requests_enabled: bool | None = None,
with_programming_language: str | None = None,
wiki_checksum_failed: bool | None = None,
repository_checksum_failed: bool | None = None,
min_access_level: int | None = None,
id_after: int | None = None,
id_before: int | None = None,
last_activity_after: str | None = None,
last_activity_before: str | None = None,
repository_storage: str | None = None,
topic: str | None = None,
**kwargs
) -> list[Project]:
"""
List projects with extensive filtering options.
Parameters:
- archived: Filter by archived status
- visibility: Filter by visibility ("private", "internal", "public")
- order_by: Order by field ("id", "name", "path", "created_at", "updated_at", "last_activity_at")
- sort: Sort direction ("asc", "desc")
- search: Search in project name and description
- search_namespaces: Include namespaces in search
- simple: Return minimal project information
- owned: Show only owned projects
- membership: Show only projects where user is member
- starred: Show only starred projects
- statistics: Include project statistics
- with_custom_attributes: Include custom attributes
- with_issues_enabled: Filter by issues enabled
- with_merge_requests_enabled: Filter by merge requests enabled
- with_programming_language: Filter by programming language
- min_access_level: Minimum access level
- id_after: Return projects with ID after this value
- id_before: Return projects with ID before this value
- last_activity_after: Filter by last activity date (ISO format)
- last_activity_before: Filter by last activity date (ISO format)
- topic: Filter by topic
Returns:
List of Project objects
"""
def get(self, id: int | str, lazy: bool = False, **kwargs) -> Project:
"""
Get a specific project.
Parameters:
- id: Project ID or path with namespace
- lazy: Return object without making API call
- statistics: Include project statistics
- license: Include license information
- with_custom_attributes: Include custom attributes
Returns:
Project object
Raises:
GitlabGetError: If project not found or access denied
"""
def create(self, data: dict, **kwargs) -> Project:
"""
Create a new project.
Parameters:
- data: Project creation parameters
Required fields in data:
- name: Project name
Optional fields in data:
- path: Project path (defaults to name)
- namespace_id: Namespace ID for project
- description: Project description
- issues_enabled: Enable issues (default: True)
- merge_requests_enabled: Enable merge requests (default: True)
- jobs_enabled: Enable CI/CD jobs (default: True)
- wiki_enabled: Enable wiki (default: True)
- snippets_enabled: Enable snippets (default: True)
- resolve_outdated_diff_discussions: Auto-resolve outdated discussions
- container_registry_enabled: Enable container registry
- shared_runners_enabled: Enable shared runners
- visibility: Project visibility ("private", "internal", "public")
- import_url: Git repository URL to import
- public_builds: Make builds public
- only_allow_merge_if_pipeline_succeeds: Require pipeline success for merge
- only_allow_merge_if_all_discussions_are_resolved: Require resolved discussions
- merge_method: Merge method ("merge", "rebase_merge", "ff")
- lfs_enabled: Enable Git LFS
- request_access_enabled: Allow access requests
- tag_list: List of project tags
- printing_merge_request_link_enabled: Print MR link after push
- build_git_strategy: Git strategy for builds
- build_timeout: Build timeout in seconds
- auto_cancel_pending_pipelines: Auto-cancel pending pipelines
- build_coverage_regex: Coverage parsing regex
- ci_config_path: CI config file path
- repository_storage: Repository storage name
- approvals_before_merge: Required approvals before merge
- external_authorization_classification_label: Classification label
- mirror: Enable repository mirroring
- mirror_user_id: Mirror user ID
- mirror_trigger_builds: Trigger builds on mirror
- initialize_with_readme: Create initial README
- template_name: Project template name
- template_project_id: Template project ID
- use_custom_template: Use custom template
- group_with_project_templates_id: Group with project templates
- packages_enabled: Enable package registry
Returns:
New Project object
Raises:
GitlabCreateError: If project creation fails
"""
def import_project(
self,
file: io.BufferedReader,
path: str,
name: str | None = None,
namespace: str | None = None,
overwrite: bool = False,
override_params: dict | None = None,
**kwargs
) -> dict:
"""
Import project from file.
Parameters:
- file: Project export file
- path: Project path
- name: Project name (optional)
- namespace: Target namespace (optional)
- overwrite: Overwrite existing project
- override_params: Override project parameters
Returns:
Dictionary with import information
"""The Project class provides access to all project-related resources through manager attributes:
# Core project resources
@property
def issues(self) -> ProjectIssueManager:
"""Access project issues."""
@property
def issues_statistics(self) -> ProjectIssuesStatisticsManager:
"""Access project issue statistics."""
@property
def mergerequests(self) -> ProjectMergeRequestManager:
"""Access project merge requests."""
@property
def milestones(self) -> ProjectMilestoneManager:
"""Access project milestones."""
@property
def labels(self) -> ProjectLabelManager:
"""Access project labels."""
# Repository and code management
@property
def commits(self) -> ProjectCommitManager:
"""Access project commits."""
@property
def branches(self) -> ProjectBranchManager:
"""Access project branches."""
@property
def tags(self) -> ProjectTagManager:
"""Access project tags."""
@property
def files(self) -> ProjectFileManager:
"""Access project repository files."""
@property
def protectedbranches(self) -> ProjectProtectedBranchManager:
"""Access protected branches."""
@property
def protectedtags(self) -> ProjectProtectedTagManager:
"""Access protected tags."""
# CI/CD resources
@property
def pipelines(self) -> ProjectPipelineManager:
"""Access project pipelines."""
@property
def jobs(self) -> ProjectJobManager:
"""Access project jobs."""
@property
def runners(self) -> ProjectRunnerManager:
"""Access project runners."""
@property
def variables(self) -> ProjectVariableManager:
"""Access project CI/CD variables."""
@property
def triggers(self) -> ProjectTriggerManager:
"""Access pipeline triggers."""
@property
def pipelineschedules(self) -> ProjectPipelineScheduleManager:
"""Access pipeline schedules."""
# Access control and members
@property
def members(self) -> ProjectMemberManager:
"""Access project members."""
@property
def members_all(self) -> ProjectMemberAllManager:
"""Access all project members including inherited."""
@property
def accessrequests(self) -> ProjectAccessRequestManager:
"""Access project access requests."""
@property
def access_tokens(self) -> ProjectAccessTokenManager:
"""Access project access tokens."""
# Deployment and environments
@property
def environments(self) -> ProjectEnvironmentManager:
"""Access project environments."""
@property
def deployments(self) -> ProjectDeploymentManager:
"""Access project deployments."""
@property
def deploytokens(self) -> ProjectDeployTokenManager:
"""Access deploy tokens."""
@property
def keys(self) -> ProjectKeyManager:
"""Access deploy keys."""
# Integration and webhooks
@property
def hooks(self) -> ProjectHookManager:
"""Access project webhooks."""
@property
def integrations(self) -> ProjectIntegrationManager:
"""Access project integrations."""
@property
def services(self) -> ProjectServiceManager:
"""Access project services (deprecated, use integrations)."""
# Additional resources (40+ more managers available)
@property
def wikis(self) -> ProjectWikiManager:
"""Access project wiki pages."""
@property
def snippets(self) -> ProjectSnippetManager:
"""Access project snippets."""
@property
def packages(self) -> ProjectPackageManager:
"""Access project packages."""
@property
def releases(self) -> ProjectReleaseManager:
"""Access project releases."""
@property
def badges(self) -> ProjectBadgeManager:
"""Access project badges."""
@property
def boards(self) -> ProjectBoardManager:
"""Access project issue boards."""import gitlab
# Initialize client
gl = gitlab.Gitlab("https://gitlab.example.com", private_token="your-token")
# List projects with filtering
projects = gl.projects.list(
owned=True,
visibility="private",
order_by="updated_at",
sort="desc",
search="api"
)
# Get specific project
project = gl.projects.get(123)
# or by path
project = gl.projects.get("group/project-name")
# Create new project
project_data = {
"name": "My New Project",
"description": "A sample project",
"visibility": "private",
"issues_enabled": True,
"merge_requests_enabled": True,
"wiki_enabled": False,
"initialize_with_readme": True
}
new_project = gl.projects.create(project_data)
# Project operations
project.star()
project.fork(namespace="my-namespace")
# Transfer project
project.transfer_project("new-namespace")
# Share project with group
project.share(group_id=456, group_access=30) # Developer access
# Get project languages
languages = project.languages()
print(f"Languages: {languages}")
# Access project resources
issues = project.issues.list(state="opened")
mrs = project.mergerequests.list(state="merged")
branches = project.branches.list()
# Project statistics
if hasattr(project, 'statistics'):
stats = project.statistics
print(f"Commit count: {stats['commit_count']}")
print(f"Storage size: {stats['storage_size']}")
# Delete project (careful!)
# project.delete()class ProjectFork(RESTObject):
"""Represents a project fork relationship."""
pass
class ProjectForkManager(ListMixin[ProjectFork]):
"""Manager for project forks."""
def list(self, **kwargs) -> list[ProjectFork]:
"""List project forks."""class ProjectGroup(RESTObject):
"""Represents a group that has access to the project."""
pass
class ProjectGroupManager(ListMixin[ProjectGroup]):
"""Manager for groups with project access."""
def list(
self,
search: str | None = None,
skip_groups: list[int] | None = None,
with_shared: bool | None = None,
shared_min_access_level: int | None = None,
shared_visible_only: bool | None = None,
**kwargs
) -> list[ProjectGroup]:
"""List groups with access to project."""class GitlabTransferProjectError(GitlabOperationError):
"""Raised when project transfer fails."""
pass
class GitlabHousekeepingError(GitlabOperationError):
"""Raised when housekeeping operation fails."""
passExample error handling:
try:
project = gl.projects.get("nonexistent/project")
except gitlab.GitlabGetError as e:
if e.response_code == 404:
print("Project not found")
elif e.response_code == 403:
print("Access denied")
else:
print(f"Error: {e}")
try:
project.transfer_project("invalid-namespace")
except gitlab.GitlabTransferProjectError as e:
print(f"Transfer failed: {e}")Install with Tessl CLI
npx tessl i tessl/pypi-python-gitlab