Skip to content

仓库 files navigation

GitLab4J™ API (gitlab4j-api)
Java Client Library for the GitLab REST API

Maven Central Build Status javadoc.io

GitLab4J™ API (gitlab4j-api) provides a full featured and easy to consume Java library for working with GitLab repositories via the GitLab REST API. Additionally, full support for working with GitLab webhooks and system hooks is also provided.


GitLab Server Version Support

GitLab4J-API supports both GitLab Community Edition (gitlab-ce) and GitLab Enterprise Edition (gitlab-ee).

NOTICE:
As of GitLab 11.0 support for the GitLab API v3 has been removed from the GitLab server (see https://about.gitlab.com/2018/06/01/api-v3-removal-impending/). Support for GitLab API v3 has been removed from this library in April 2025.


Using GitLab4J-API

Java 11 Requirement

As of GitLab4J-API 6.0.0, Java 11+ is now required to use GitLab4J-API.

Javadocs

Javadocs are available here: javadoc.io

Project Set Up

To utilize GitLab4J™ API in your Java project, simply add the following dependency to your project's build file:

Gradle: build.gradle

dependencies {
    ...
    implementation group: 'org.gitlab4j', name: 'gitlab4j-api', version: '6.3.0'
}

Maven: pom.xml

<dependency>
    <groupId>org.gitlab4j</groupId>
    <artifactId>gitlab4j-api</artifactId>
    <version>6.3.0</version>
</dependency>

Jbang:

Jbang is very convinient to run scripts writen in Java having dependencies on third party libraries.

Just add this line at the top of your script:

//DEPS org.gitlab4j:gitlab4j-api:6.3.0

Ivy and SBT
There have been reports of problems resolving some dependencies when using Ivy or SBT, for help resolving those issues see:
JAX-RS API Issue #571
JAX-RS API Issue #572

Lastest version

While we are frequently creating releases, you might be interested by a feature that has not been published yet. You can use jars created by jitpack to get the newest version.

Usage with gradle:

repositories {
    mavenCentral()
    maven {
        url "https://jitpack.io"
        content {
            includeGroup "com.github.gitlab4j.gitlab4j-api"
        }
    }
}

dependencies {
    // ...
    implementation 'com.github.gitlab4j.gitlab4j-api:gitlab4j-api:main-SNAPSHOT'
    // ...
}

Usage with maven:

<repositories>
  <repository>
    <id>jitpack.io</id>
    <url>https://jitpack.io</url>
  </repository>
</repositories>

<dependencies>
  <dependency>
    <groupId>com.github.gitlab4j.gitlab4j-api</groupId>
    <artifactId>gitlab4j-api</artifactId>
    <version>main-SNAPSHOT</version>
  </dependency>
  <!-- ... -->
</dependencies>

Usage with jbang:

You just need to declare the dependency like this, instead of using the maven coordinates:

//DEPS https://github.com/gitlab4j/gitlab4j-api/tree/main#gitlab4j-api:SNAPSHOT

Using a specific commit

Version main-SNAPSHOT indicates that you would like to get the latest of the main branch. You can also point to a specific commit:

dependencies {
    implementation 'com.github.gitlab4j.gitlab4j-api:gitlab4j-api:ab6b84c6b0'
}
<dependency>
    <groupId>com.github.gitlab4j.gitlab4j-api</groupId>
    <artifactId>gitlab4j-api</artifactId>
    <version>ab6b84c6b0</version>
</dependency>
//DEPS https://github.com/gitlab4j/gitlab4j-api/tree/ab6b84c6b096ea3079d25115a59c272a4ae602aa

Models jar

For some usages, the HTTP layer based on Jersey can't be used. Those projects might want to use the Jackson-based model classes, and implement the REST call themself.

Gradle: build.gradle

dependencies {
    ...
    implementation 'org.gitlab4j:gitlab4j-models:6.3.0'
}

Maven: pom.xml

<dependency>
    <groupId>org.gitlab4j</groupId>
    <artifactId>gitlab4j-models</artifactId>
    <version>6.3.0</version>
</dependency>

Usage Examples

GitLab4J-API is quite simple to use, all you need is the URL to your GitLab server and the Personal Access Token from your GitLab Account 设置 page. Once you have that info it is as simple as:

// Create a GitLabApi instance to communicate with your GitLab server
GitLabApi gitLabApi = new GitLabApi("http://your.gitlab.server.com", "YOUR_PERSONAL_ACCESS_TOKEN");

// Get the list of projects your account has access to
List<Project> projects = gitLabApi.getProjectApi().get项目();

You can also login to your GitLab server with username, and password:

// Log in to the GitLab server using a username and password
GitLabApi gitLabApi = GitLabApi.oauth2Login("http://your.gitlab.server.com", "username", "password");

As of GitLab4J-API 4.6.6, all API requests support performing the API call as if you were another user, provided you are authenticated as an administrator:

// Create a GitLabApi instance to communicate with your GitLab server (must be an administrator)
GitLabApi gitLabApi = new GitLabApi("http://your.gitlab.server.com", "YOUR_PERSONAL_ACCESS_TOKEN");

// sudo as as a different user, in this case the user named "johndoe", all future calls will be done as "johndoe"
gitLabApi.sudo("johndoe")

// To turn off sudo mode
gitLabApi.unsudo();

Setting Request Timeouts

As of GitLab4J-API 4.14.21 support has been added for setting the conect and read timeouts for the API client:

GitLabApi gitLabApi = new GitLabApi("http://your.gitlab.com", "YOUR_PERSONAL_ACCESS_TOKEN", proxyConfig);

// Set the connect timeout to 1 second and the read timeout to 5 seconds
gitLabApi.setRequestTimeout(1000, 5000);

Connecting Through a Proxy Server

As of GitLab4J-API 4.8.2 support has been added for connecting to the GitLab server using an HTTP proxy server:

// Log in to the GitLab server using a proxy server (with basic auth on proxy)
Map<String, Object> proxyConfig = ProxyClientConfig.createProxyClientConfig(
        "http://your-proxy-server", "proxy-username", "proxy-password");
GitLabApi gitLabApi = new GitLabApi("http://your.gitlab.com", "YOUR_PERSONAL_ACCESS_TOKEN", null, proxyConfig);

// Log in to the GitLab server using a proxy server (no auth on proxy)
Map<String, Object> proxyConfig = ProxyClientConfig.createProxyClientConfig("http://your-proxy-server");
GitLabApi gitLabApi = new GitLabApi("http://your.gitlab.com", "YOUR_PERSONAL_ACCESS_TOKEN", null, proxyConfig);

// Log in to the GitLab server using an NTLM (Windows DC) proxy
Map<String, Object> ntlmProxyConfig = ProxyClientConfig.createNtlmProxyClientConfig(
        "http://your-proxy-server", "windows-username", "windows-password", "windows-workstation", "windows-domain");
GitLabApi gitLabApi = new GitLabApi("http://your.gitlab.com", "YOUR_PERSONAL_ACCESS_TOKEN", null, ntlmProxyConfig);

See the Javadoc on the GitLabApi class for a complete list of methods accepting the proxy configuration (clientConfiguration parameter)


GitLab API V3 and V4 Support

As of GitLab4J-API 4.2.0 support has been added for GitLab API V4. If your application requires GitLab API V3, you can still use GitLab4J-API by creating your GitLabApi instance as follows:

// Create a GitLabApi instance to communicate with your GitLab server using GitLab API V3
GitLabApi gitLabApi = new GitLabApi(ApiVersion.V3, "http://your.gitlab.server.com", "YOUR_PRIVATE_TOKEN");

NOTICE:
As of GitLab 11.0 support for the GitLab API v3 has been removed from the GitLab server (see https://about.gitlab.com/2018/06/01/api-v3-removal-impending/). Support for GitLab API v3 will be removed from this library sometime in 2019. If you are utilizing the v3 support, please update your code to use GitLab API v4.


Logging of API Requests and Responses

As of GitLab4J-API 4.8.39 support has been added to log the requests to and the responses from the GitLab API. Enable logging using one of the following methods on the GitLabApi instance:

GitLabApi gitLabApi = new GitLabApi("http://your.gitlab.server.com", "YOUR_PERSONAL_ACCESS_TOKEN");

// Log using the shared logger and default level of FINE
gitLabApi.enableRequestResponseLogging();

// Log using the shared logger and the INFO level
gitLabApi.enableRequestResponseLogging(java.util.logging.Level.INFO);

// Log using the specified logger and the INFO level
gitLabApi.enableRequestResponseLogging(yourLoggerInstance, java.util.logging.Level.INFO);

// Log using the shared logger, at the INFO level, and include up to 1024 bytes of entity logging
gitLabApi.enableRequestResponseLogging(java.util.logging.Level.INFO, 1024);

// Log using the specified logger, at the INFO level, and up to 1024 bytes of entity logging
gitLabApi.enableRequestResponseLogging(yourLoggerInstance, java.util.logging.Level.INFO, 1024);

Results Paging

GitLab4J-API provides an easy to use paging mechanism to page through lists of results from the GitLab API. Here are a couple of examples on how to use the Pager:

// Get a Pager instance that will page through the projects with 10 projects per page
Pager<Project> projectPager = gitLabApi.getProjectApi().get项目(10);

// Iterate through the pages and print out the name and description
while (projectPager.hasNext()) {
    for (Project project : projectPager.next()) {
        System.out.println(project.getName() + " -: " + project.getDescription());
    }
}

As of GitLab4J-API 4.9.2, you can also fetch all the items as a single list using a Pager instance:

// Get a Pager instance so we can load all the projects into a single list, 10 items at a time:
Pager<Project> projectPager = gitlabApi.get项目Api().get项目(10);
List<Project> all项目 = projectPager.all();

Java 8 Stream Support

As of GitLab4J-API 4.9.2, all GitLabJ-API methods that return a List result have a similarlly named method that returns a Java 8 Stream. The Stream returning methods use the following naming convention: getXxxxxStream().

IMPORTANT
The built-in methods that return a Stream do so using eager evaluation, meaning all items are pre-fetched from the GitLab server and a Stream is returned which will stream those items. Eager evaluation does NOT support parallel reading of data from ther server, it does however allow for parallel processing of the Stream post data fetch.

To stream using lazy evaluation, use the GitLab4J-API methods that return a Pager instance, and then call the lazyStream() method on the Pager instance to create a lazy evaluation Stream. The Stream utilizes the Pager instance to page through the available items. A lazy Stream does NOT support parallel operations or skipping.

Eager evaluation example usage:

// Stream the visible projects printing out the project name.
Stream<Project> projectStream = gitlabApi.getProjectApi().get项目Stream();
projectStream.map(Project::getName).forEach(name -> System.out.println(name));

// Operate on the stream in parallel, this example sorts User instances by username
// NOTE: Fetching of the users is not done in parallel,
// only the sorting of the users is a parallel operation.
Stream<User> stream = gitlabApi.getUserApi().getUsersStream();
List<User> users = stream.parallel().sorted(comparing(User::getUsername)).collect(toList());

Lazy evaluation example usage:

// Get a Pager instance to that will be used to lazily stream Project instances.
// In this example, 10 项目 per page will be pre-fetched.
Pager<Project> projectPager = gitlabApi.getProjectApi().get项目(10);

// Lazily stream the 项目, printing out each project name, limit the output to 5 project names
projectPager.lazyStream().limit(5).map(Project::getName).forEach(name -> System.out.println(name));

Java 8 Optional Support

GitLab4J-API supports Java 8 Optional<T> for API calls that result in the return of a single item. Here is an example on how to use the Java 8 Optional<T> API calls:

Optional<Group> optionalGroup =  gitlabApi.getGroupApi().getOptionalGroup("my-group-path");
if (optionalGroup.isPresent())
    return optionalGroup.get();

return gitlabApi.getGroupApi().addGroup("my-group-name", "my-group-path");

Issue Time Estimates

GitLab issues allow for time tracking. The following time units are currently available:

  • months (mo)
  • weeks (w)
  • days (d)
  • hours (h)
  • minutes (m)

Conversion rates are 1mo = 4w, 1w = 5d and 1d = 8h.


Making API Calls

The API has been broken up into sub API classes to make it easier to consume and to separate concerns. The GitLab4J sub API classes typically have a one-to-one relationship with the API documentation at GitLab API. 已关注 is a sample of the GitLab4J sub API class mapping to the GitLab API documentation:

org.gitlab4j.api.GroupApi -> https://docs.gitlab.com/ce/api/groups.html
org.gitlab4j.api.MergeRequestApi -> https://docs.gitlab.com/ce/api/merge_requests.html
org.gitlab4j.api.ProjectApi -> https://docs.gitlab.com/ce/api/projects.html
org.gitlab4j.api.UserApi -> https://docs.gitlab.com/ce/api/users.html

Available Sub APIs

The following is a list of the available sub APIs along with a sample use of each API. See the Javadocs for a complete list of available methods for each sub API.


  ApplicationsApi
  Application设置Api
  AuditEventApi
  AwardEmojiApi
  BoardsApi
  提交Api
  ContainerRegistryApi
  DeployKeysApi
  讨论Api
  环境Api
  EpicsApi
  EventsApi
  GroupApi
  HealthCheckApi
  ImportExportApi
  问题Api
  JobApi
  标签Api
  LicenseApi
  LicenseTemplatesApi
  标签Api
  MergeRequestApi
  里程碑Api
  NamespaceApi
  NotesApi
  Notification设置Api
  包Api
  PipelineApi
  ProjectApi
  Protected分支Api
  发布Api
  仓库Api
  仓库FileApi
  ReourceLabelEventsApi
  RunnersApi
  搜索Api
  ServicesApi
  SessionApi
  SnippetsApi
  SystemHooksApi
  标签Api
  TodosApi
  UserApi
  维基sApi

Sub API Examples


ApplicationsApi

// Add an OAUTH Application to GitLab
ApplicationScope[] scopes = {ApplicationScope.SUDO, ApplicationScope.PROFILE};
gitLabApi.getApplicationsApi().createApplication("My OAUTH Application", "https//example.com/myapp/callback", scopes);

Application设置Api

// Get the current GitLab server application settings
Application设置 app设置 = gitLabApi.getApplication设置Api().getAppliation设置();

AuditEventApi

// Get the current GitLab server audit events for entity
// This uses the ISO8601 date utilities the in org.gitlab4j.api.utils.ISO8601 class
Date since = ISO8601.toDate("2017-01-01T00:00:00Z");
Date until = new Date(); // now
List<AuditEvent> auditEvents = gitLabApi.getAuditEventApi().getAuditEvents(since, until, EntityType.USER, 1);

AwardEmojiApi

// Get a list of AwardEmoji belonging to the specified issue (group ID = 1, issues IID = 1)
List<AwardEmoji> awardEmojis = gitLabApi.getAwardEmojiApi().getIssuAwardEmojis(1, 1);

BoardsApi

// Get a list of the Issue Boards belonging to the specified project
List<Board> boards = gitLabApi.getBoardsApi().getBoards(projectId);

提交Api

// Get a list of commits associated with the specified branch that fall within the specified time window
// This uses the ISO8601 date utilities the in org.gitlab4j.api.utils.ISO8601 class
Date since = ISO8601.toDate("2017-01-01T00:00:00Z");
Date until = new Date(); // now
List<Commit> commits = gitLabApi.get提交Api().get提交(1234, "new-feature", since, until);

ContainerRegistryApi

// Get a list of the registry repositories belonging to the specified project
List<Registry仓库> registryRepos = gitLabApi.ContainerRegistryApi().get仓库(projectId);

DeployKeysApi

// Get a list of DeployKeys for the authenticated user
List<DeployKey> deployKeys = gitLabApi.getDeployKeysApi().getDeployKeys();

讨论Api

// Get a list of 讨论 for the specified merge request
List<Discussion> discussions = gitLabApi.get讨论Api().getMergeRequest讨论(projectId, mergeRequestIid);

环境Api

// Get a list of 环境 for the specified project
List<Environment> environments = gitLabApi.get环境Api().get环境(projectId);

EpicsApi

// Get a list epics of the requested group and its subgroups.
List<Epic> epics = gitLabApi.getEpicsApi().getEpics(1);

EventsApi

// Get a list of Events for the authenticated user
Date after = new Date(0); // After Epoch
Date before = new Date(); // Before now
List<Event> events = gitLabApi.getEventsApi().getAuthenticatedUserEvents(null, null, before, after, DESC);

GroupApi

// Get a list of groups that you have access to
List<Group> groups = gitLabApi.getGroupApi().getGroups();

HealthCheckApi

// Get the liveness endpoint health check results. Assumes ip_whitelisted per:
// https://docs.gitlab.com/ee/administration/monitoring/ip_whitelist.html
HealthCheckInfo healthCheck = gitLabApi.getHealthCheckApi().getLiveness();

ImportExportApi

// Schedule a project export for the specified project ID
gitLabApi.getImportExportApi().scheduleExport(projectId);

// Get the project export status for the specified project ID
ExportStatus exportStatus = gitLabApi.getImportExportApi().getExportStatus(projectId);

问题Api

// Get a list of issues for the specified project ID
List<Issue> issues = gitLabApi.get问题Api().get问题(1234);

JobApi

// Get a list of jobs for the specified project ID
List<Job> jobs = gitLabApi.getJobApi().getJobs(1234);

标签Api

// Get a list of labels for the specified project ID
List<Label> labels = gitLabApi.get标签Api().get标签(1234);

LicenseApi

// Retrieve information about the current license
License license = gitLabApi.getLicenseApi().getLicense();

LicenseTemplatesApi

// Get a list of open sourcse license templates
List<LicenseTemplate> licenses = gitLabApi.getLicenseTemplatesApi().getLicenseTemplates();

MergeRequestApi

// Get a list of the merge requests for the specified project
List<MergeRequest> mergeRequests = gitLabApi.getMergeRequestApi().getMergeRequests(1234);

里程碑Api

// Get a list of the milestones for the specified project
List<Milestone> milestones = gitLabApi.get里程碑Api().get里程碑(1234);

NamespaceApi

// Get all namespaces that match "foobar" in their name or path
List<Namespace> namespaces = gitLabApi.getNamespaceApi().findNamespaces("foobar");

NotesApi

// Get a list of the issues's notes for project ID 1234, issue IID 1
List<Note> notes = gitLabApi.getNotesApi().getNotes(1234, 1);

Notification设置Api

// Get the current global notification settings
Notification设置 settings = gitLabApi.getNotification设置Api().getGlobalNotification设置();

包Api

// Get all packages for the specified project ID
List<> packages = gitLabApi.get包Api().get包(1234);

PipelineApi

// Get all pipelines for the specified project ID
List<Pipeline> pipelines = gitLabApi.getPipelineApi().getPipelines(1234);

ProjectApi

// Get a list of accessible projects 
public List<Project> projects = gitLabApi.getProjectApi().get项目();
// Create a new project
Project projectSpec = new Project()
    .withName("my-project")
    .withDescription("My project for demonstration.")
    .with问题Enabled(true)
    .withMergeRequestsEnabled(true)
    .with维基Enabled(true)
    .withSnippetsEnabled(true)
    .withPublic(true);

Project newProject = gitLabApi.getProjectApi().createProject(projectSpec);

Protected分支Api

List<ProtectedBranch> branches = gitLabApi.getProtected分支Api().getProtected分支(project.getId());

发布Api

// Get a list of releases for the specified project
List<Release> releases = gitLabApi.get发布Api().get发布(projectId);

仓库Api

// Get a list of repository branches from a project, sorted by name alphabetically
List<Branch> branches = gitLabApi.get仓库Api().get分支(projectId);
// 搜索 repository branches from a project, by name
List<Branch> branches = gitLabApi.get仓库Api().get分支(projectId, searchTerm);

仓库FileApi

// Get info (name, size, ...) and the content from a file in repository
仓库File file = gitLabApi.get仓库FileApi().getFile("file-path", 1234, "ref");   

ResourceLabelEventsApi

// Get the label events for the specified merge request
List<LabelEvent> labelEvents = gitLabApi.getResourceLabelEventsApi()
        .getMergeRequestLabelEvents(projectId, mergeRequestIid);

RunnersApi

// Get All Runners.
List<Runner> runners = gitLabApi.getRunnersApi().getAllRunners();

搜索Api

// Do a global search for 项目
List<Project> projects = gitLabApi.get搜索Api().global搜索(搜索Scope.PROJECTS, "text-to-search-for");

ServicesApi

// Activate/Update the Slack 通知 service
SlackService slackService =  new SlackService()
        .withMergeRequestsEvents(true)
        .withWebhook("https://hooks.slack.com/services/ABCDEFGHI/KJLMNOPQR/wetrewq7897HKLH8998wfjjj")
        .withUsername("GitLab4J");
gitLabApi.getServicesApi().updateSlackService("project-path", slackService);

SessionApi

// Log in to the GitLab server and get the session info
gitLabApi.getSessionApi().login("your-username", "your-email", "your-password");

SnippetsApi

// Get a list of the authenticated user's snippets
List<Snippet> snippets = gitLabApi.getSnippetsApi().getSnippets();

SystemHooksApi

// Get a list of installed system hooks
List<SystemHook> hooks = gitLabApi.getSystemHooksApi().getSystemHooks();

标签Api

// Get a list of tags for the specified project ID
List<Tag> tags = gitLabApi.get标签Api().get标签(projectId);

TodosApi

// Get a list of all pending todos for the current user
List<Todo> todos = gitLabApi.getTodosApi().gePendingTodos();

UserApi

// Get the User info for user_id 1
User user = gitLabApi.getUserApi().getUser(1);

// Create a new user with no password who will recieve a reset password email
User userConfig = new User()
    .withEmail("jdoe@example.com")
    .withName("Jane Doe")
    .withUsername("jdoe");
String password = null;
boolean sendResetPasswordEmail = true;
gitLabApi.getUserApi().createUser(userConfig, password, sendResetPasswordEmail);

维基sApi

// Get a list of pages in project wiki
List<维基Page> wikiPages = gitLabApi.get维基sApi().getPages();

关于

GitLab4J API (gitlab4j-api) provides a full featured Java client library for working with GitLab repositories via the GitLab REST API

Topics

Resources

Code of conduct

Stars

1.2k stars

关注者

30 watching

复刻s

发布

Used by

贡献者

Languages