Home > Software engineering >  GitLab API - find GitLab Project ID by repo URL
GitLab API - find GitLab Project ID by repo URL

Time:07-29

I have a GitLab repo url, trying to find the project ID using GitLab API. looking at this https://docs.gitlab.com/ee/api/projects.html#list-all-projects page I didn't find the option to search by repo url.

eg.

Given this URL https://gitlab.com/gitlab-learn-labs/gitops/classgroup-unilogik-2/shanekba/world-greetings-env-1

Find the Project ID: 38149446

Is there an option to find this project id?

Thanks

CodePudding user response:

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/gitops/classgroup-unilogik-2/shanekba/world-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//'\/'//}"  # 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