杰瑞科技汇

Python GitLab API 怎么用?

Of course! Using the Python GitLab API is a common task for automating interactions with GitLab. The most popular and recommended library for this is python-gitlab.

Python GitLab API 怎么用?-图1
(图片来源网络,侵删)

Here's a comprehensive guide covering everything from installation to practical examples.


The Recommended Library: python-gitlab

This is the official, community-maintained Python wrapper for the GitLab API. It's well-documented, actively developed, and supports both the REST API and the GraphQL API.

Installation

You can install it using pip:

pip install python-gitlab

Authentication

Before you can interact with GitLab, you need to authenticate. python-gitlab supports several methods. The most common are:

Python GitLab API 怎么用?-图2
(图片来源网络,侵删)

Method 1: Personal Access Token (Recommended)

This is the most straightforward method for scripts and personal automation.

  1. Generate a token in GitLab:

    • Go to your GitLab profile -> Settings -> Access Tokens.
    • Give your token a name (e.g., python-scripts).
    • Set an expiration date.
    • Select the necessary scopes (permissions). For read-only, read_api is enough. For creating projects or issues, you'll need write_api, read_repository, read_user, etc.
    • Click Create personal access token. Copy the token immediately, as you won't be able to see it again.
  2. Use the token in your Python script:

    import gitlab
    # Replace with your GitLab URL and the token you generated
    gl = gitlab.Gitlab('https://gitlab.example.com', private_token='your_access_token_here')
    # Optional: Verify connection
    try:
        gl.auth()
        print(f"Connected to GitLab as {gl.user.name} ({gl.user.username})")
    except Exception as e:
        print(f"Authentication failed: {e}")

Method 2: OAuth2 Token

Similar to a Personal Access Token but generated via the OAuth2 flow. Useful if you're building an application that acts on behalf of a user.

import gitlab
gl = gitlab.Gitlab('https://gitlab.example.com', oauth_token='your_oauth_token_here')
gl.auth()

Method 3: Job Token (For CI/CD)

If your script is running inside a GitLab CI/CD job, you can use the built-in CI_JOB_TOKEN for authentication.

import gitlab
import os
# The CI_JOB_TOKEN is automatically available in CI/CD environments
gl = gitlab.Gitlab('https://gitlab.example.com', job_token=os.getenv('CI_JOB_TOKEN'))
gl.auth()

Basic Usage & Common Examples

Once authenticated, you can start interacting with GitLab resources. The library provides an object-oriented interface.

List all projects

# Get a list of all projects the authenticated user has access to
projects = gl.projects.list()
for project in projects:
    print(f"Project: {project.path_with_namespace} (ID: {project.id})")

Get a specific project

You can find a project by its ID or its full path (e.g., group/subgroup/project-name).

# Get project by its full path (recommended)
project = gl.projects.get('my-group/my-project')
# Or by ID
# project = gl.projects.get(123)
print(f"Project Name: {project.name}")
print(f"Project Description: {project.description}")

List project members

project = gl.projects.get('my-group/my-project')
members = project.members.list()
for member in members:
    print(f"User: {member.username} has access level: {member.access_level}")

Create a new issue

project = gl.projects.get('my-group/my-project')
# Create a new issue
issue = project.issues.create({: 'This is a new issue from Python',
    'description': 'Created using the python-gitlab library.',
    'labels': ['bug', 'automation'] # Optional
})
print(f"Created issue #{issue.iid}: {issue.title}")

List issues with filtering

You can pass keyword arguments to the list() method to filter results, just like in the GitLab UI.

project = gl.projects.get('my-group/my-project')
# Find all open issues with the 'bug' label
issues = project.issues.list(state='opened', labels=['bug'])
for issue in issues:
    print(f"#{issue.iid}: {issue.title}")

Create a new merge request

project = gl.projects.get('my-group/my-project')
# Create a new merge request
# You need to specify the source and target branch names
mr = project.mergerequests.create({
    'source_branch': 'feature/new-login',
    'target_branch': 'main',: 'Add new login functionality',
    'description': 'This MR introduces the new login feature.',
    'labels': ['feature', 'backend']
})
print(f"Created MR !{mr.iid}: {mr.title}")

List all groups

groups = gl.groups.list()
for group in groups:
    print(f"Group: {group.full_path} (ID: {group.id})")

Get a specific group and list its projects

group = gl.groups.get('my-group')
# List projects belonging to the group
projects = group.projects.list()
for project in projects:
    print(f"  - Project: {project.path_with_namespace}")

Advanced Features

Pagination

GitLab API results are paginated. The list() method handles this automatically by returning a GitlabList object, which acts like a Python list but fetches pages as you iterate.

# The list object will fetch pages of 20 items by default
# You can specify a per_page value (max 100)
issues = gl.projects.get('my-group/my-project').issues.list(per_page=50)
# You can iterate through all issues across all pages
for issue in issues:
    print(f"#{issue.iid}: {issue.title}")

If you need to manually control pagination, you can use the iterator() method.

# Get an iterator for all issues, fetching 100 at a time
issue_iterator = gl.projects.get('my-group/my-project').issues.list(iterator=True, per_page=100)
for issue in issue_iterator:
    print(f"Processing issue #{issue.iid}")

Pagination using page and per_page

# Get the first page of 5 projects
page1 = gl.projects.list(per_page=5)
# Get the second page
page2 = gl.projects.list(per_page=5, page=2)

Rate Limiting

GitLab API has rate limits. The python-gitlab library helps you manage this.

import time
import gitlab
gl = gitlab.Gitlab('https://gitlab.example.com', private_token='your_token')
# The library will automatically sleep and retry if it hits the rate limit.
# You can also check the rate limit status.
rate_limit = gl.rate_limit
print(f"Requests remaining: {rate_limit['remaining']}")
print(f"Limit resets at: {rate_limit['reset']}")
# Now perform your actions. The library will handle waiting if needed.
projects = gl.projects.list()

Using the GraphQL API

python-gitlab also supports the GraphQL API, which can be more efficient for complex data queries.

# First, get a GraphQL client
graphql = gl.graphql
# Define your GraphQL query
query = """
query {
  project(fullPath: "my-group/my-project") {
    name
    issues(state: opened) {
      nodes {
        title
        createdAt
      }
    }
  }
}
"""
# Execute the query
result = graphql.execute(query)
# Process the result
project_data = result['data']['project']
print(f"Project: {project_data['name']}")
for issue in project_data['issues']['nodes']:
    print(f"  - {issue['title']} (created: {issue['createdAt']})")

Error Handling

It's good practice to handle potential errors, such as a project not being found or permissions being denied.

import gitlab
gl = gitlab.Gitlab('https://gitlab.example.com', private_token='your_token')
try:
    # This will raise a gitlab.exceptions.GitlabError if the project doesn't exist
    project = gl.projects.get('non-existent-project')
    print(project.name)
except gitlab.exceptions.GitlabError as e:
    print(f"An error occurred: {e}")
    # e.response will contain the full response object from the requests library
    # print(e.response.json())

Useful Resources

分享:
扫描分享到社交APP
上一篇
下一篇