Getting started overview

This guide outlines the initial steps for developers to begin using GitLab, focusing on account setup, authentication, and making a first API request. GitLab provides a unified platform for the entire DevOps lifecycle, facilitating collaboration, version control, continuous integration, and continuous deployment. The GitLab API allows programmatic interaction with its features, enabling automation and integration with other systems.

To follow this guide, you will need:

  • A web browser to access the GitLab interface.
  • A command-line tool or an HTTP client (e.g., cURL, Postman) to make API requests.
  • Basic familiarity with Git and HTTP requests.

The process generally involves creating a GitLab account, generating an access token for API authentication, and then using this token to perform an operation, such as listing your projects via the GitLab REST API.

Create an account and get keys

To interact with GitLab, you first need an account. GitLab offers various options, including a free tier suitable for individuals and small teams, as well as paid tiers for more advanced features and larger organizations. You can sign up for a free account directly on the GitLab homepage.

Account Creation

  1. Navigate to the GitLab registration page.
  2. Enter your full name, username, email address, and a strong password.
  3. Complete the CAPTCHA verification.
  4. Click Register.
  5. Verify your email address by clicking the link sent to your registered email.

Authentication Methods

GitLab supports several methods for authenticating API requests:

  • Personal Access Tokens (PATs): These are alphanumeric strings that grant access to your GitLab account via the API. PATs can be scoped to specific permissions and have an expiration date. They are the recommended method for individual API access and scripting.
  • OAuth 2.0: Used for third-party applications or when you need to grant limited access to your GitLab account without sharing your password. GitLab acts as an OAuth 2.0 provider, allowing applications to request specific permissions from users. For more details on this flow, refer to the GitLab OAuth 2.0 documentation.
  • CI/CD Job Tokens: Automatically generated tokens available within GitLab CI/CD jobs, providing temporary authentication for operations within the pipeline.
  • Deploy Tokens: Credentials used to grant read-only or read/write access to project repositories and package registries without using a user account.

For getting started, Personal Access Tokens are the most straightforward approach.

Generate a Personal Access Token (PAT)

  1. Log in to your GitLab account.
  2. In the top-right corner, click on your avatar and select Edit profile.
  3. In the left sidebar, select Access Tokens.
  4. Enter a descriptive Token name (e.g., MyFirstAPIToken).
  5. Set an Expiration date. While optional, it's a security best practice to set an expiration.
  6. Select the desired Scopes. For your first request, select read_api to allow reading data via the API. For broader access, you might select api, which grants full read/write access to the authenticated user's projects, groups, and other resources.
  7. Click Create personal access token.
  8. Important: Copy the generated token immediately. GitLab will not display it again after you leave the page. Store it securely, as it grants access to your account.

For more detailed information on creating and managing PATs, consult the GitLab Personal Access Tokens guide.

Your first request

Once you have generated a Personal Access Token, you can make your first API request to GitLab. This example demonstrates how to list your accessible projects using the GitLab REST API. The base URL for the GitLab API is typically https://gitlab.com/api/v4 for the cloud-hosted version, or your self-hosted instance's URL followed by /api/v4.

Listing Projects with cURL

Open your terminal or command prompt and execute the following cURL command. Replace <YOUR_PERSONAL_ACCESS_TOKEN> with the token you generated.

curl --header "PRIVATE-TOKEN: <YOUR_PERSONAL_ACCESS_TOKEN>" \
     "https://gitlab.com/api/v4/projects"

If successful, the API will return a JSON array containing information about the projects you have access to. The output will resemble the following (truncated for brevity):

[
  {
    "id": 123456,
    "description": null,
    "name": "my-example-project",
    "name_with_namespace": "Your Username / my-example-project",
    "path": "my-example-project",
    "path_with_namespace": "your-username/my-example-project",
    "created_at": "2023-01-01T12:00:00.000Z",
    "default_branch": "main",
    "ssh_url_to_repo": "[email protected]:your-username/my-example-project.git",
    "http_url_to_repo": "https://gitlab.com/your-username/my-example-project.git",
    "web_url": "https://gitlab.com/your-username/my-example-project",
    "readme_url": "https://gitlab.com/your-username/my-example-project/-/blob/main/README.md",
    "tag_list": [],
    "topics": [],
    "star_count": 0,
    "forks_count": 0,
    "avatar_url": null,
    "public": true,
    "visibility": "private",
    "_links": {
      "self": "https://gitlab.com/api/v4/projects/123456",
      "issues": "https://gitlab.com/api/v4/projects/123456/issues",
      "merge_requests": "https://gitlab.com/api/v4/projects/123456/merge_requests",
      "repo_branches": "https://gitlab.com/api/v4/projects/123456/repository/branches",
      "labels": "https://gitlab.com/api/v4/projects/123456/labels",
      "members": "https://gitlab.com/api/v4/projects/123456/members"
    },
    // ... more project details
  }
  // ... more projects
]

Using an SDK

GitLab officially supports several client libraries and SDKs, including Ruby, Python, Go, Java, and JavaScript. Using an SDK can simplify API interactions by handling authentication, request formatting, and response parsing. Below is an example using the python-gitlab library.

Python SDK Example

First, install the python-gitlab library:

pip install python-gitlab

Then, create a Python script (e.g., list_projects.py) with the following content:

import gitlab

# Private token or CI/CD job token. You can also use an OAuth token.
# Make sure to replace <YOUR_PERSONAL_ACCESS_TOKEN> with your actual token.
# For self-hosted instances, replace 'https://gitlab.com' with your GitLab URL.
gl = gitlab.Gitlab('https://gitlab.com', private_token='<YOUR_PERSONAL_ACCESS_TOKEN>')

# Verify authentication (optional, but good for debugging)
gl.auth()

# Get a list of projects
projects = gl.projects.list(all=True) # all=True to retrieve all projects, not just the first page

for project in projects:
    print(f"Project ID: {project.id}, Name: {project.name}, Web URL: {project.web_url}")

Run the script:

python list_projects.py

This script will print the ID, name, and web URL for each project accessible by your token. For more examples and detailed usage of the Python client, refer to the python-gitlab documentation.

Common next steps

After successfully making your first API call, consider these next steps to further integrate with GitLab:

  1. Explore the API Reference: The GitLab API Reference is comprehensive, detailing endpoints for projects, repositories, users, issues, merge requests, CI/CD, and more. Understanding the available endpoints will enable you to automate various DevOps tasks.
  2. Set up a Project: Create a new project in GitLab, initialize a Git repository, and push some code. This provides a sandbox to experiment with the platform's features and API interactions.
  3. Integrate with CI/CD: Explore GitLab CI/CD pipelines to automate testing, building, and deploying your applications. The API can be used to trigger pipelines, retrieve job status, and manage CI/CD variables.
  4. Webhooks: Configure webhooks to receive real-time notifications about events in your GitLab projects (e.g., push events, merge request updates, issue comments). This allows for event-driven automation and integration with other services. For example, you can send notifications to a messaging platform or trigger an external process. Details on setting up webhooks are available in the GitLab webhooks documentation.
  5. Advanced Authentication: For production applications or broader integrations, investigate OAuth 2.0 for more secure and controlled access to user data without direct token management.
  6. Explore GitLab Ecosystem: Consider using GitLab's built-in container registry, package registry, or integrated security scanning features to streamline your development workflow.

Troubleshooting the first call

Encountering issues during your first API call is common. Here's a table of common problems and their solutions:

Problem Likely Cause Solution
401 Unauthorized Incorrect or missing Personal Access Token (PAT). Double-check the PAT for typos. Ensure it's passed in the PRIVATE-TOKEN header. Regenerate if unsure. Verify the token hasn't expired.
403 Forbidden Insufficient permissions (scopes) for the PAT. Ensure the PAT has the necessary scopes (e.g., read_api for read operations, api for full access). Regenerate the token with broader scopes if needed.
404 Not Found Incorrect API endpoint or resource ID. Verify the URL path and resource IDs (e.g., project ID). Ensure you are using the correct base URL (https://gitlab.com/api/v4 for cloud, or your self-hosted instance's URL).
JSON parsing errors Invalid JSON response or network issue. Check the full response body for error messages. Ensure your cURL command or HTTP client is correctly configured to handle JSON.
Connection timeout Network issues or GitLab service unavailability. Check your internet connection. Verify GitLab's service status page. Try the request again after a short delay.
Token was copied incorrectly (missing characters) Human error during token generation/copying. Regenerate the PAT and ensure it is copied entirely and accurately. Store it in a temporary text file to avoid truncation or errors.

For persistent issues, consult the GitLab API documentation for specific error codes and troubleshooting guides. Additionally, reviewing server logs (if self-hosting) or GitLab's operational status can provide further insights.