API


Overview

GitLab offers a very extensive API

The API is located at /api/v4/

The notes how to use the API include:

Resources

Resources for every aspect of GitLab


Authentication

Authentication using a token (personal/group/project)

Token requires read_api or api scope

Send token in HTTP header using Private-Token:

curl "http://gitlab.${DOMAIN}/api/v4/projects" \
    --silent \
    --verbose \
    --header "Private-Token: <your_access_token>"

Pagination

Pagination done by offset

GitLab API returns HTTP headers:

Header Description
x-next-page Index of next page
x-page Index of current page
x-per-page Number of items per page
x-prev-page Index of previous page
x-total Total number of items
x-total-pages Total number of pages

Keyset-based pagination is also supported


Hands-On (1/2)

cURL

  1. Retrieve projects using a private access token:

     curl http://gitlab.${DOMAIN}/api/v4/projects \
         --silent \
         --header "Private-Token: <TOKEN>"
    

  2. Check pagination headers:

     curl http://gitlab.${DOMAIN}/api/v4/projects \
         --silent \
         --verbose \
         --header "Private-Token: <TOKEN>"
    


Hands-On (2/2)

glab

glab was adopted as the official CLI in November 2022:

  1. Configure glab:

     glab auth login --hostname gitlab.${DOMAIN}
    

  2. Search for projects:

     GL_HOST=gitlab.${DOMAIN} glab repo search -s foo
    

  3. Send raw API requests with automatic pagination:

     GL_HOST=gitlab.${DOMAIN} glab api --paginate /projects
    


Token expiry and rotation

Expiry

Token without expiry are a security threat

GitLab 16.0 (May 2023) sets a 1-year lifetime on such tokens

Rotation

Rotation API introduced in GitLab 16.0 (May 2023)

Automatic reuse detection prevents use of rotated tokens: