Search code examples
pythonjsongitgitlabgitlab-api

GitLab API - How to GET the repository/project files and metadata?


I am new to GitLab and using API calls and am confused on how to make a call to get the repository/project files and metadata. My current API call is as follows:

https://gitlab.com/api/v3/projects?private_token=privateToken

privateToken at the end of the line above is replaced with my private token which I have taken out for obvious security reasons.

This will return to me the json that describes all of the projects I have, but I want to drill down deeper and see the specific information about the files that are stored within each project/repository. On the GitLab API documentation website, it lists this:

GET /projects/:id/repository/files/:file_path

However, since I am new to GitLab and API calls in general I am confused as to how to edit my first link to retrieve this information.

Ideally, I would like to be able to drill down to the project/repository files and metadata within python and not have to edit the first link above, but I am not sure if that is possible. How does GitLab return the json? As a hash table of hash tables, if so, how do I navigate through it?

Any clarification on how to parse through the json and drilling deeper within it would be greatly appreciated!

I am using Python 3.6.1.


Solution

  • You've partly answered your own question in the comment (you can post that as an answer).

    As for the :file_path, take a look at the API for repo files.

    GET /projects/:id/repository/files/:file_path
    

    CURLing:

    curl --request GET --header 'PRIVATE-TOKEN: 9koXpg98eAheJpvBs5tK' \
    'https://gitlab.example.com/api/v4/projects/13083/repository/files/app%2Fmodels%2Fkey%2Erb?ref=master'
    

    You haven't given a file_path you want to use, so taking gitlab-ce as an example - the file "app/models/key.rb", is url-encoded to app%2Fmodels%2Fkey%2Erb:

    curl --request GET \
    'https://gitlab.com/api/v3/projects/13083/repository/files/app%2Fmodels%2Fkey%2Erb?ref=master'
    

    The project id can be specified as the integer id or the URL-encoded path. So instead of 13083, the project namespace gitlab-org/gitlab-ce url-encoded can be used as:

    curl --request GET \
    'https://gitlab.com/api/v3/projects/gitlab-org%2Fgitlab-ce/repository/files/app%2Fmodels%2Fkey%2Erb?ref=master'
    

    You may also want to look at using an existing API like pyapi-gitlab.