@gitbeaker/rest

中文文档
44.1.3发布于 2026/11/16MITTypeScriptES Module近 30 天下载 823.4万

Cross Platform implementation of the GitLab API

原始使用文档
文档目录10 节
  1. Table of Contents
  2. Features
  3. Usage
  4. API Client
  5. Expanded Payloads
  6. Pagination
  7. Rate Limits
  8. Error Handling
  9. Examples
  10. Contributors


gitbeaker



CircleCI REST Coverage Auto All Contributors Prettier Licence: MIT Install Size: Rest

A Typed GitLab SDK for Browsers, Node.js, and Deno.

Table of Contents

Features

  • Complete - All features of GitLab's exposed APIs are covered up to version 16.5. See here for the full list.
  • Universal - Works in all modern browsers, Node.js, and Deno.
  • Tested - All libraries have > 80% test coverage.
  • Typed - All libraries have extensive TypeScript declarations.

Usage

Browsers Load @gitbeaker/rest directly from esm.sh
<script type="module">
  import { Gitlab } from 'https://esm.sh/@gitbeaker/rest';
</script>
Deno Load @gitbeaker/rest directly from esm.sh
import { Gitlab } from 'https://esm.sh/@gitbeaker/rest?dts';
Node 18+

Install with npm install @gitbeaker/rest, yarn add @gitbeaker/rest, or pnpm add @gitbeaker/rest

import { Gitlab } from '@gitbeaker/rest';

API Client

Instantiate the library using a basic token created in your GitLab Profile

const api = new Gitlab({
  token: 'personaltoken',
});

Available instantiating options:

NameOptionalDefaultDescription
hostYeshttps://gitlab.comGitlab Instance Host URL
tokenYes*N/APersonal Token. Recommended (one of the three tokens are recommended)
oauthTokenYes*N/AOAuth Token. Recommended (one of the three tokens are recommended)
jobTokenYes*N/ACI Job Token. Recommended (one of the three tokens are recommended)
rejectUnauthorizedYestrueHttp Certificate setting, Only applies to non-browser releases and HTTPS hosts urls
sudoYesfalseSudo query parameter
camelizeYesfalseCamelizes all response body keys
requesterFnNo@gitbeaker/rest & @gitbeaker/cli : fetch-based, The @gitbeaker/core package does not have a default and thus must be set explicitlyRequest Library Wrapper
queryTimeoutYes300000Query Timeout in ms
profileTokenYesN/ARequests Profiles Token
profileModeYesexecutionRequests Profiles Token
rateLimitsNoDEFAULT_RATE_LIMITSGlobal and endpoint specific adjustable rate limits
rateLimitDurationNo60Timeout duration when rate limit is reached

*One of these options should be supplied, as most API requests require authentication.

Expanded Payloads

For simplicity, only the response body is returned from the API methods. However, seeing additional response fields, such as the status, headers, etc., may be helpful. For this purpose, an additional optional parameter, showExpanded can be passed for most API methods.

For methods that return non-paginated results, the payload has this structure:

type ResponseBodyTypes =
  | Record<string, unknown>
  | Record<string, unknown>[]
  | ReadableStream
  | Blob
  | string
  | string[]
  | number
  | void
  | null;

interface FormattedResponse<T extends ResponseBodyTypes = ResponseBodyTypes> {
  body: T;
  headers: Record<string, string>;
  status: number;
}

For methods that return paginated results, the payload also includes paginated information outlined in the Pagination documentation

Pagination

Available pagination options:

NameKeysetOffsetTypeDefaultDescription
paginationXX'offset' or 'keyset''offset'Defines which pagination type should be used
perPageXXNumber20Amount of results per request
orderByXStringWhat field the results should be ordered by
sortX'asc' or 'desc''asc'The direction of sort for the results
maxPagesXNumberN/AMaximum amount of requests that should be made
pageXNumberN/ASpecific page to be retrieved
showExpandedXBooleanfalseReturns with the pagination information in addition to the data

Offset Pagination

For any .all() function on a resource, it will return all the items from GitLab. This can be troublesome if there are many items, as the request itself can take a while to be fulfilled. As such, a maxPages option can be passed to limit the scope of the all function.

import { Gitlab } from '@gitbeaker/rest';

const api = new Gitlab({
  host: 'http://example.com',
  token: 'personaltoken',
});

let projects = await api.Projects.all({ maxPages: 2 });

You can also use this in conjunction with the perPage argument which would override the default of 30 per page set by Gitlab:

import { Gitlab } from '@gitbeaker/rest';

const api = new Gitlab({
  host: 'http://example.com',
  token: 'personaltoken',
});

let projects = await api.Projects.all({ maxPages: 2, perPage: 40 });

Additionally, if you would like to get back the pagination information, to know how many total pages there are for example, pass the option showExpanded. If there are multiple results the pagination property will be included as shown below:

...
const { data, paginationInfo } = await api.Projects.all({
  perPage:40,
  maxPages:2,
  showExpanded: true
});
...

This will result in a response in this format:

data: [
...
],
paginationInfo: {
  next: 4,
  current: 2,
  previous: 1,
  perPage: 3,
}

Note: Supplying any pagination restrictions is call intensive. Some resources will require many requests which can put a significant load on the GitLab Server. The general best practice would be setting the page request option to only return the first page if all results are not required.

Keyset Pagination

Similarly, support for Keyset pagination can be toggled on by passing a pagination parameter as a query option

const { data } = await api.Projects.all({
  pagination: 'keyset',
  sort: 'asc',
  orderBy: 'created_at',
});

Rate Limits

Rate limits are completely customizable, and are used to limit the request rate between consecutive API requests within the library. By default, all non-specified endpoints use a 3000 rps rate limit, while some endpoints have much smaller rates as dictated by the GitLab Docs. See below for the default values:

const DEFAULT_RATE_LIMITS = Object.freeze({
  // Default rate limit
  '**': 3000,

  // Import/Export
  'projects/import': 6,
  'projects/*/export': 6,
  'projects/*/download': 1,
  'groups/import': 6,
  'groups/*/export': 6,
  'groups/*/download': 1,

  // Note creation
  'projects/*/issues/*/notes': {
    method: 'post',
    limit: 300,
  },
  'projects/*/snippets/*/notes': {
    method: 'post',
    limit: 300,
  },
  'projects/*/merge_requests/*/notes': {
    method: 'post',
    limit: 300,
  },
  'groups/*/epics/*/notes': {
    method: 'post',
    limit: 300,
  },

  // Repositories - get file archive
  'projects/*/repository/archive*': 5,

  // Project Jobs
  'projects/*/jobs': 600,

  // Member deletion
  'projects/*/members': 60,
  'groups/*/members': 60,
});

Rate limits can be overridden when instantiating a API wrapper. For ease of use, these limits are configured using glob patterns, and can be formatted in two ways.

  1. The glob for the endpoint with the corresponding rate per second
  2. The glob for the endpoint, with an object specifying the specific method for the endpoint and the corresponding rate limit

You can also override the rateLimitDuration default value of 60 seconds. This is how long a specific endpoint will be timed out for when its rate limit is reached.

const api = new Gitlab({
  token: 'token',
  rateLimits: {
    '**': 30,
    'projects/import/*': 40,
    'projects/*/issues/*/notes': {
      method: 'post',
      limit: 300,
    },
  },
  rateLimitDuration: 30,
});

Error Handling

Request errors are returned back within a plain Error instance, using the cause to hold the original response and a text description of the error pulled from the response's error or message fields if JSON, or its plain text value:

class GitbeakerError extends Error {
  constructor(
    message: string,
    options?: {
      cause: {
        description: string;
        request: Request;
        response: Response;
      };
    },
  ) {
    super(message, options);
    this.name = 'GitbeakerError';
  }
}

Note, the message is assigned to the Response's statusText, and the Request and Response types are from the NodeJS API.

Examples

Once you have your library instantiated, you can utilize many of the API's functionality:

Using the await/async method

import { Gitlab } from '@gitbeaker/rest';

const api = new Gitlab({
  host: 'http://example.com',
  token: 'personaltoken',
});

// Listing users
let users = await api.Users.all();

// Or using Promise-Then notation
api.Projects.all().then((projects) => {
  console.log(projects);
});

A general rule about all the function parameters:

  • If it's a required parameter, it is a named argument in the functions
  • If it's an optional parameter, it is defined in a options object following the named arguments

ie.

import { Projects } from '@gitbeaker/rest';

const projectsAPI = new Projects({
  host: 'http://example.com',
  token: 'personaltoken',
});

projectsAPI.create({
  //options defined in the GitLab API documentation
});

Contributors

Justin Dalrymple Dylan DesRosier Mike Wyatt Cory Zibeill Martin Bour akira345 Pavel Birukov Joseph Petersen Louis Cherel Adam Dehnel Ev Haus Loïc Mahieu Giuseppe Angri jennparise Oscar Daniel Ruf schindld Alvaro Daniel Moore Dylan M. Taylor Corentin Mors xatavian Yevgeny Petukhov Mickaël Tricot Andrea Flavien Bridault s-kazuki Kipras Melnikovas xieyu st1gok Max Wittig Niklas Lochschmidt Ilya Dus Omar Awamry Hennadii Varava xiezht Martin Helmich Sean McGivern Clemens Lieb Vojtěch Sajdl divido Vincent Boulaye Aliyss Snow Mahmoud Saada Feng Yu Roy Jacobs Paul Lemke Ian Jenkins nilennoct Laffargue Michael Martin Howarth Christoph Lehmann Frank V Salim Benabbou Tamás Török-Vistai Martin Benninger fewieden Jeff Pelton Claude Abounegm Stefan Hall Jordan Wallet zhao0 Joshua Grosso Isaac Ouellet Therrien Rajat Sharma Cesar B. Igor Katsuba Michael Townsend bodtx Artem Munif Tanjim Quentin Dreyer Norm MacLennan jnovick Fabian Aussems Michael Matzka CraigAllardyce Bruno Guimarães Lukas Eipert Maximilian Krauß Evolution Engineering WEBER Logan Anton Zhukov Nicholas Loomans Carl Kittelberger Patrik Votoček Kyrylo Fedorov Claudio Vellage Seb0uil Rafael Mello Théis Bazin Spencer Salisbury Simone Corsi Bambii Will ArnaudTA Benjamin Beret Alessandro Diez artlist-scottambrose Martin Dreher Elan Ruusamäe artemoire Pieter Willekens David Claybourne Dom Harrington Kohei Seino JounQin Elaine Mattos DK Koen Brouwer Sefa Eyeoglu Carmi Raz Arnold Hendriks Baylee Schmeisser Andy roberta-pavel Youssef Miguel Giannis Kepas Talysson de Oliveira Cassiano Marco Endrik Einberg Bryan Lee Zack Kay W. Florian Imdahl lanthier ShaoWei Teo Daniel Rentz Matěj Smíšek

This started as a fork from node-gitlab-legacy but I ended up rewriting much of the code. Here are the original work's contributors.

版本与发布记录

@gitbeaker/rest 共发布 158 个版本,首次发布于 2023/03/14;过去 12 个月发布了 29 个版本。

版本发布日期距今
44.1.3latest2026/11/16今天
44.1.22026/11/16今天
44.1.12026/11/16今天
44.1.02026/11/16今天
44.0.72026/11/16今天
44.0.62026/11/151 天前

其他发布通道:canary → 0.0.0-canary-20260813022219,pre → 44.0.0-pre.0。

关于 @gitbeaker/rest 的常见问题

@gitbeaker/rest 是什么?

Cross Platform implementation of the GitLab API

如何安装 @gitbeaker/rest?

在项目目录运行 npm install @gitbeaker/rest,或使用 pnpm add / yarn add / bun add。

@gitbeaker/rest 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@gitbeaker/rest 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@gitbeaker/rest 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=v24.16.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@gitbeaker/rest 可以商用吗?

@gitbeaker/rest 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@gitbeaker/rest 的下载量有多少?

根据 npm 官方下载统计,@gitbeaker/rest 在 2026/10/17 – 2026/11/15 这 30 天内被下载 8,234,360 次,日均约 274,479 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@gitbeaker/rest 还在维护吗?

最新版本 44.1.3 发布于 2026/11/16(今天);至今共发布 158 个版本,其中过去 12 个月发布了 29 个;首次发布于 2023/03/14。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。