0
# Client and Authentication
1
2
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.
3
4
## Capabilities
5
6
### Gitlab Client Initialization
7
8
The main Gitlab client class that manages server connections, authentication, and API access. Supports multiple authentication methods and extensive configuration options.
9
10
```python { .api }
11
class Gitlab:
12
def __init__(
13
self,
14
url: str | None = None,
15
private_token: str | None = None,
16
oauth_token: str | None = None,
17
job_token: str | None = None,
18
ssl_verify: bool | str = True,
19
http_username: str | None = None,
20
http_password: str | None = None,
21
timeout: float | None = None,
22
api_version: str = "4",
23
per_page: int | None = None,
24
pagination: str | None = None,
25
order_by: str | None = None,
26
user_agent: str = "python-gitlab/6.3.0",
27
retry_transient_errors: bool = False,
28
keep_base_url: bool = False,
29
**kwargs
30
) -> None:
31
"""
32
Initialize GitLab client with connection and authentication parameters.
33
34
Parameters:
35
- url: The URL of the GitLab server (defaults to https://gitlab.com)
36
- private_token: User private token for authentication
37
- oauth_token: OAuth token for authentication
38
- job_token: CI job token for authentication
39
- ssl_verify: Whether to verify SSL certificates (bool) or path to CA file (str)
40
- http_username: Username for HTTP basic authentication
41
- http_password: Password for HTTP basic authentication
42
- timeout: Request timeout in seconds
43
- api_version: GitLab API version to use (only "4" supported)
44
- per_page: Default number of items per page for pagination
45
- pagination: Pagination method ("keyset" for keyset pagination)
46
- order_by: Default ordering for list operations
47
- user_agent: Custom user agent string
48
- retry_transient_errors: Whether to retry on 5xx errors
49
- keep_base_url: Keep user-provided base URL for pagination
50
"""
51
```
52
53
#### Configuration-based Initialization
54
55
```python { .api }
56
@classmethod
57
def from_config(
58
cls,
59
gitlab_id: str = "global",
60
config_files: list[str] | None = None
61
) -> Gitlab:
62
"""
63
Create Gitlab instance from configuration file.
64
65
Parameters:
66
- gitlab_id: Configuration section name (default: "global")
67
- config_files: List of configuration file paths
68
69
Returns:
70
Configured Gitlab instance
71
"""
72
```
73
74
Usage example:
75
```python
76
# From default config file locations
77
gl = gitlab.Gitlab.from_config()
78
79
# From specific config file and section
80
gl = gitlab.Gitlab.from_config("my-gitlab", ["/path/to/config.cfg"])
81
```
82
83
### Authentication and User Management
84
85
```python { .api }
86
def auth(self) -> CurrentUser:
87
"""
88
Authenticate with GitLab and return current user.
89
90
Returns:
91
CurrentUser object representing the authenticated user
92
93
Raises:
94
GitlabAuthenticationError: If authentication fails
95
"""
96
97
def version(self) -> dict:
98
"""
99
Get GitLab server version information.
100
101
Returns:
102
Dictionary with version, revision, and other server details
103
"""
104
```
105
106
Usage examples:
107
```python
108
import gitlab
109
110
# Authenticate with private token
111
gl = gitlab.Gitlab("https://gitlab.example.com", private_token="glpat-xxxx")
112
user = gl.auth()
113
print(f"Logged in as: {user.name} ({user.username})")
114
115
# Check server version
116
version_info = gl.version()
117
print(f"GitLab version: {version_info['version']}")
118
```
119
120
### HTTP Request Methods
121
122
Low-level HTTP methods for direct API access when higher-level methods don't suffice.
123
124
```python { .api }
125
def http_get(
126
self,
127
path: str,
128
query_data: dict | None = None,
129
streamed: bool = False,
130
raw: bool = False,
131
**kwargs
132
) -> Any:
133
"""
134
Perform HTTP GET request.
135
136
Parameters:
137
- path: API endpoint path
138
- query_data: Query parameters dictionary
139
- streamed: Whether to return streaming response
140
- raw: Whether to return raw response object
141
142
Returns:
143
Response data (dict/list/bytes depending on content type)
144
"""
145
146
def http_post(
147
self,
148
path: str,
149
post_data: dict | None = None,
150
raw: bool = False,
151
files: dict | None = None,
152
**kwargs
153
) -> Any:
154
"""
155
Perform HTTP POST request.
156
157
Parameters:
158
- path: API endpoint path
159
- post_data: Request body data
160
- raw: Whether to return raw response object
161
- files: Files to upload
162
163
Returns:
164
Response data
165
"""
166
167
def http_put(
168
self,
169
path: str,
170
put_data: dict | None = None,
171
raw: bool = False,
172
files: dict | None = None,
173
**kwargs
174
) -> Any:
175
"""Perform HTTP PUT request."""
176
177
def http_patch(
178
self,
179
path: str,
180
patch_data: dict | None = None,
181
raw: bool = False,
182
files: dict | None = None,
183
**kwargs
184
) -> Any:
185
"""Perform HTTP PATCH request."""
186
187
def http_delete(self, path: str, **kwargs) -> Any:
188
"""Perform HTTP DELETE request."""
189
190
def http_head(self, path: str, **kwargs) -> Any:
191
"""Perform HTTP HEAD request."""
192
193
def http_list(
194
self,
195
path: str,
196
query_data: dict | None = None,
197
**kwargs
198
) -> GitlabList:
199
"""
200
Perform HTTP GET request returning paginated list.
201
202
Returns:
203
GitlabList object with pagination support
204
"""
205
```
206
207
### Global Search and Utilities
208
209
```python { .api }
210
def search(
211
self,
212
scope: str,
213
search: str,
214
**kwargs
215
) -> list[dict]:
216
"""
217
Perform global search across GitLab instance.
218
219
Parameters:
220
- scope: Search scope ("projects", "issues", "merge_requests", "milestones", "snippet_titles", "users")
221
- search: Search query string
222
223
Returns:
224
List of search results
225
"""
226
227
def markdown(
228
self,
229
text: str,
230
project: str | None = None,
231
gfm: bool = False
232
) -> dict:
233
"""
234
Render Markdown text using GitLab's Markdown processor.
235
236
Parameters:
237
- text: Markdown text to render
238
- project: Project context for rendering (for project-specific references)
239
- gfm: Whether to use GitHub Flavored Markdown
240
241
Returns:
242
Dictionary with rendered HTML
243
"""
244
245
def get_license(self) -> dict:
246
"""Get GitLab license information (GitLab EE only)."""
247
248
def set_license(self, license: str) -> dict:
249
"""Set GitLab license (GitLab EE only)."""
250
```
251
252
### Configuration Management
253
254
```python { .api }
255
class GitlabConfigParser:
256
def __init__(self, config_files: list[str] | None = None) -> None:
257
"""
258
Initialize configuration parser.
259
260
Parameters:
261
- config_files: List of configuration file paths to read
262
"""
263
264
def get_gitlab_config(self, gitlab_id: str = "global") -> dict:
265
"""
266
Get configuration for specific GitLab instance.
267
268
Parameters:
269
- gitlab_id: Configuration section name
270
271
Returns:
272
Dictionary with configuration parameters
273
"""
274
```
275
276
Example configuration file (`~/.python-gitlab.cfg`):
277
```ini
278
[global]
279
default = local
280
ssl_verify = true
281
timeout = 60
282
283
[local]
284
url = https://gitlab.example.com
285
private_token = glpat-xxxxxxxxxxxxxxxxxxxx
286
api_version = 4
287
288
[gitlab-com]
289
url = https://gitlab.com
290
private_token = glpat-yyyyyyyyyyyyyyyyyyyy
291
```
292
293
### Authentication Backends
294
295
```python { .api }
296
class PrivateTokenAuth:
297
"""Private token authentication backend."""
298
def __init__(self, token: str) -> None: ...
299
300
class OAuthTokenAuth:
301
"""OAuth token authentication backend."""
302
def __init__(self, token: str) -> None: ...
303
304
class JobTokenAuth:
305
"""CI job token authentication backend."""
306
def __init__(self, token: str) -> None: ...
307
```
308
309
### Error Handling for Authentication
310
311
```python { .api }
312
class GitlabAuthenticationError(GitlabError):
313
"""Raised when authentication fails."""
314
pass
315
316
class GitlabConnectionError(GitlabError):
317
"""Raised when connection to GitLab server fails."""
318
pass
319
320
class GitlabHttpError(GitlabError):
321
"""Raised for HTTP-level errors."""
322
pass
323
```
324
325
Example error handling:
326
```python
327
try:
328
gl = gitlab.Gitlab("https://gitlab.example.com", private_token="invalid")
329
user = gl.auth()
330
except gitlab.GitlabAuthenticationError:
331
print("Invalid authentication credentials")
332
except gitlab.GitlabConnectionError:
333
print("Unable to connect to GitLab server")
334
except gitlab.GitlabHttpError as e:
335
print(f"HTTP error {e.response_code}: {e.error_message}")
336
```
337
338
### Session and Connection Management
339
340
```python { .api }
341
@property
342
def user(self) -> CurrentUser | None:
343
"""Get currently authenticated user (if authenticated)."""
344
345
@property
346
def server_version(self) -> str | None:
347
"""Get GitLab server version string."""
348
349
@property
350
def server_revision(self) -> str | None:
351
"""Get GitLab server revision hash."""
352
353
@property
354
def api_url(self) -> str:
355
"""Get full API URL."""
356
357
@property
358
def api_version(self) -> str:
359
"""Get API version being used."""
360
```
361
362
### Manager Access Properties
363
364
The Gitlab client provides direct access to all resource managers:
365
366
```python { .api }
367
# Project and repository managers
368
@property
369
def projects(self) -> ProjectManager: ...
370
@property
371
def groups(self) -> GroupManager: ...
372
@property
373
def users(self) -> UserManager: ...
374
375
# Administrative managers
376
@property
377
def runners(self) -> RunnerManager: ...
378
@property
379
def settings(self) -> ApplicationSettingsManager: ...
380
@property
381
def features(self) -> FeatureManager: ...
382
383
# And 100+ more resource managers...
384
```
385
386
This provides convenient access to all GitLab resources:
387
```python
388
gl = gitlab.Gitlab(url, token)
389
390
# Access projects
391
projects = gl.projects.list()
392
393
# Access users
394
users = gl.users.list()
395
396
# Access runners
397
runners = gl.runners.list()
398
```