GitLab API - find GitLab Project ID by repo URL

Viewed 97
1 Answers

You can use the path of the repo to access project info from the API. You just need to URL-encode the path.

Using the projects API

project_path="gitlab-learn-labs%2fgitops%2fclassgroup-unilogik-2%2fshanekba%2fworld-greetings-env-1"
url="https://gitlab.com/api/v4/projects/${project_path}"
curl -s "${url}" | jq .id

Output:

38149446

As a complete example starting from the original URL:

project_url="https://gitlab.com/gitlab-learn-labs/gitops/classgroup-unilogik-2/shanekba/world-greetings-env-1"

project_path="$(cut -d/ -f4- <<< ${project_url})"
urlencoded_path="${project_path//'\/'/%2f}"  # use `urlencode` if installed, but this works in a pinch
curl -s "https://gitlab.com/api/v4/projects/${urlencoded_path}" | jq .id

Using GraphQL

Alternatively, you can use the graphql API. A graphql query like:

{
  project(fullPath: "gitlab-org/gitlab") {
    fullPath
    id
  }
}

Will produce the ID in the response:

{
  "data": {
    "project": {
      "fullPath": "gitlab-org/gitlab",
      "id": "gid://gitlab/Project/278964"
    }
  }
}
Related