Getting started with the API

python-gitlab only supports GitLab API v4.

gitlab.Gitlab class

To connect to or another GitLab instance, create a gitlab.Gitlab object:


You can use different types of tokens for authenticated requests against the GitLab API. You will most likely want to use a resource (project/group) access token or a personal access token.

For the full list of available options and how to obtain these tokens, please see

import gitlab

# anonymous read-only access for public resources (
gl = gitlab.Gitlab()

# anonymous read-only access for public resources (self-hosted GitLab instance)
gl = gitlab.Gitlab('')

# private token or personal token authentication (
gl = gitlab.Gitlab(private_token='JVNSESs8EwWRx5yDxM5q')

# private token or personal token authentication (self-hosted GitLab instance)
gl = gitlab.Gitlab(url='', private_token='JVNSESs8EwWRx5yDxM5q')

# oauth token authentication
gl = gitlab.Gitlab('', oauth_token='my_long_token_here')

# job token authentication (to be used in CI)
# bear in mind the limitations of the API endpoints it supports:
import os
gl = gitlab.Gitlab('', job_token=os.environ['CI_JOB_TOKEN'])

# Define your own custom user agent for requests
gl = gitlab.Gitlab('', user_agent='my-package/1.0.0')

# make an API request to create the gl.user object. This is not required but may be useful
# to validate your token authentication. Note that this will not work with job tokens.

# Enable "debug" mode. This can be useful when trying to determine what
# information is being sent back and forth to the GitLab server.
# Note: this will cause credentials and other potentially sensitive
# information to be printed to the terminal.

You can also use configuration files to create gitlab.Gitlab objects:

gl = gitlab.Gitlab.from_config('somewhere', ['/tmp/gl.cfg'])

See the Configuration section for more information about configuration files.


Note that a url that results in 301/302 redirects will raise an error, so it is highly recommended to use the final destination in the url field. For example, if the GitLab server you are using redirects requests from http to https, make sure to use the https:// protocol in the URL definition.

A URL that redirects using 301/302 (rather than 307/308) will most likely cause malformed POST and PUT requests.

python-gitlab will therefore raise a RedirectionError when it encounters a redirect which it believes will cause such an error, to avoid confusion between successful GET and failing POST/PUT requests on the same instance.

Note on password authentication

GitLab has long removed password-based basic authentication. You can currently still use the resource owner password credentials flow to obtain an OAuth token.

However, we do not recommend this as it will not work with 2FA enabled, and GitLab is removing ROPC-based flows without client IDs in a future release. We recommend you obtain tokens for automated workflows as linked above or obtain a session cookie from your browser.

For a python example of password authentication using the ROPC-based OAuth2 flow, see this Ansible snippet.


The gitlab.Gitlab class provides managers to access the GitLab resources. Each manager provides a set of methods to act on the resources. The available methods depend on the resource type.


# list all the projects
projects = gl.projects.list(iterator=True)
for project in projects:

# get the group with id == 2
group = gl.groups.get(2)
for project in group.projects.list(iterator=True):


Calling list() without any arguments will by default not return the complete list of items. Use either the get_all=True or iterator=True parameters to get all the items when using listing methods. See the Pagination section for more information.

# create a new user
user_data = {'email': '', 'username': 'jen', 'name': 'Jen'}
user = gl.users.create(user_data)


python-gitlab attempts to sync the required, optional, and mutually exclusive attributes for resource creation and update with the upstream API.

You are encouraged to follow upstream API documentation for each resource to find these - each resource documented here links to the corresponding upstream resource documentation at the top of the page.

The attributes of objects are defined upon object creation, and depend on the GitLab API itself. To list the available information associated with an object use the attributes attribute:

project = gl.projects.get(1)

Some objects also provide managers to access related GitLab resources:

# list the issues for a project
project = gl.projects.get(1)
issues = project.issues.list(get_all=True)

python-gitlab allows to send any data to the GitLab server when making queries. In case of invalid or missing arguments python-gitlab will raise an exception with the GitLab server error message:

>>> gl.projects.list(sort='invalid value')
GitlabListError: 400: sort does not have a valid value

Conflicting Parameters

You can use the query_parameters argument to send arguments that would conflict with python or python-gitlab when using them as kwargs:

gl.user_activities.list(from='2019-01-01', iterator=True)  ## invalid

gl.user_activities.list(query_parameters={'from': '2019-01-01'}, iterator=True)  # OK

Gitlab Objects

You can update or delete a remote object when it exists locally:

# update the attributes of a resource
project = gl.projects.get(1)
project.wall_enabled = False
# don't forget to apply your changes on the server:

# delete the resource

Some classes provide additional methods, allowing more actions on the GitLab resources. For example:

# star a git repository
project = gl.projects.get(1)

You can print a Gitlab Object. For example:

project = gl.projects.get(1)

# Or in a prettier format.

# Or explicitly via ``pformat()``. This is equivalent to the above.

You can also extend the object if the parameter isn’t explicitly listed. For example, if you want to update a field that has been newly introduced to the Gitlab API, setting the value on the object is accepted:

issues = project.issues.list(state='opened')
for issue in issues:
   issue.my_super_awesome_feature_flag = "random_value"

As a dictionary

You can get a dictionary representation copy of the Gitlab Object. Modifications made to the dictionary will have no impact on the GitLab Object.

  • asdict() method. Returns a dictionary representation of the Gitlab object.

  • attributes property. Returns a dictionary representation of the Gitlab

    object. Also returns any relevant parent object attributes.

project = gl.projects.get(1)
project_dict = project.asdict()

# Or a dictionary representation also containing some of the parent attributes
issue = project.issues.get(1)
attribute_dict = issue.attributes

# The following will return the same value
title = issue.title
title = issue.attributes["title"]


This can be used to access attributes that clash with python-gitlab’s own methods or managers. Note that:

attributes returns the parent object attributes that are defined in object._from_parent_attrs. For example, a ProjectIssue object will have a project_id key in the dictionary returned from attributes but asdict() will not.


You can get a JSON string represenation of the Gitlab Object. For example:

project = gl.projects.get(1)
# Use arguments supported by ``json.dump()``
print(project.to_json(sort_keys=True, indent=4))

Base types

The gitlab package provides some base types.

  • gitlab.Gitlab is the primary class, handling the HTTP requests. It holds the GitLab URL and authentication information.

  • gitlab.base.RESTObject is the base class for all the GitLab v4 objects. These objects provide an abstraction for GitLab resources (projects, groups, and so on).

  • gitlab.base.RESTManager is the base class for v4 objects managers, providing the API to manipulate the resources and their attributes.

Lazy objects

To avoid useless API calls to the server you can create lazy objects. These objects are created locally using a known ID, and give access to other managers and methods.

The following example will only make one API call to the GitLab server to star a project (the previous example used 2 API calls):

# star a git repository
project = gl.projects.get(1, lazy=True)  # no API call  # API call

head() methods

All endpoints that support get() and list() also support a head() method. In this case, the server responds only with headers and not the response JSON or body. This allows more efficient API calls, such as checking repository file size without fetching its content.


In some cases, GitLab may omit specific headers. See more in the Pagination section.

# See total number of personal access tokens for current user

# See returned content-type for project GET endpoint
headers = gl.projects.head("gitlab-org/gitlab")


You can use pagination to iterate over long lists. All the Gitlab objects listing methods support the page and per_page parameters:

ten_first_groups = gl.groups.list(page=1, per_page=10)


The first page is page 1, not page 0.

By default GitLab does not return the complete list of items. Use the get_all parameter to get all the items when using listing methods:

all_groups = gl.groups.list(get_all=True)

all_owned_projects = gl.projects.list(owned=True, get_all=True)

You can define the per_page value globally to avoid passing it to every list() method call:

gl = gitlab.Gitlab(url, token, per_page=50)

Gitlab allows to also use keyset pagination. You can supply it to your project listing, but you can also do so globally. Be aware that GitLab then also requires you to only use supported order options. At the time of writing, only order_by="id" works.

gl = gitlab.Gitlab(url, token, pagination="keyset", order_by="id", per_page=100)


list() methods can also return a generator object, by passing the argument iterator=True, which will handle the next calls to the API when required. This is the recommended way to iterate through a large number of items:

items = gl.groups.list(iterator=True)
for item in items:

The generator exposes extra listing information as received from the server:

  • current_page: current page number (first page is 1)

  • prev_page: if None the current page is the first one

  • next_page: if None the current page is the last one

  • per_page: number of items per page

  • total_pages: total number of pages available. This may be a None value.

  • total: total number of items in the list. This may be a None value.


For performance reasons, if a query returns more than 10,000 records, GitLab does not return the total_pages or total headers. In this case, total_pages and total will have a value of None.

For more information see:


Prior to python-gitlab 3.6.0 the argument as_list was used instead of iterator. as_list=False is the equivalent of iterator=True.


If page and iterator=True are used together, the latter is ignored.


If you have the administrator status, you can use sudo to act as another user. For example:

p = gl.projects.create({'name': 'awesome_project'}, sudo='user1')


To enable debug logging from the underlying requests and http.client calls, you can use enable_debug() on your Gitlab instance. For example:

import os
import gitlab

gl = gitlab.Gitlab(private_token=os.getenv("GITLAB_TOKEN"))

By default, python-gitlab will mask the token used for authentication in logging output. If you’d like to debug credentials sent to the API, you can disable masking explicitly:


Attributes in updated objects

When methods manipulate an existing object, such as with refresh() and save(), the object will only have attributes that were returned by the server. In some cases, such as when the initial request fetches attributes that are needed later for additional processing, this may not be desired:

project = gl.projects.get(1, statistics=True)

project.statistics # AttributeError

To avoid this, either copy the object/attributes before calling refresh()/save() or subsequently perform another get() call as needed, to fetch the attributes you want.