Search code examples
githubgraphqlgithub-api

How to get content of a repository through GitHub API v4?


I'm trying to migrate my project from GitHub API v3 to v4. How to get the files or directories of a repository through GraphQL API just like what I've done with the following RESTful API in v3: GET /repos/:owner/:repo/contents/:path ?

I've read the document of GitHub API v4 but failed to find anything about it.


Solution

  • For searching the directory:

    query {
      repository(name: "<repo>", owner: "<owner>") {
        object(expression: "master:") {
          ... on Tree {
            entries {
              name
            }
          }
        }
      }
    }
    

    And for getting the file content:

    query { 
      repository(name: "<repo>", owner: "<owner>") {
        object(expression: "master:<path>") {
          ... on Blob {
            oid
            byteSize
            text
          }
        }
      }
    }
    

    Reference: https://github.community/t5/GitHub-API-Development-and/GraphQL-getting-filename-file-content-and-commit-date/td-p/17861