Search code examples
javagitlabgitlab-api

How do I retrieve a file from the gitlab repository branch using Java?


This is my GitLab structure

  • Project X
    • Repository J
      • Branches 1
        • File A
        • File B
      • Branches 2
        • File C
        • File D

I want to retrieve File A from Branches 1 Repository J using Java Code. Is there a way on how to do it? I've been looking for this method but can't find it.


Solution

  • You can retrieve a file from a repository using the Repository Files API:

    GITLAB="gitlab.example.com"
    PROJECT_ID=13083
    FILE_PATH="/path/to/filename.java"
    BRANCH_NAME="main"
    
    curl --header "PRIVATE-TOKEN: <your_access_token>" "https://${GITLAB}/api/v4/projects/${PROJECT_ID}/repository/files/${FILE_PATH}?ref=${BRANCH_NAME}"
    

    Most of this is pretty clear, but you can get the Project ID from the Projects API response, or from the Project page in Gitlab right under the project name. The File Path should be the path to the file from the root of your project. The ref parameter can be either a branch name, tag name, or a commit sha.