33

Does GitHub's GraphQL API have an equivalent to the contents API?

I can't seem to come up with a query that accepts repo owner, repo name and file path and returns the contents of the file. I'm guessing it has something to do with the tree object?

https://developer.github.com/early-access/graphql/explorer/

Jeremy Danyow
  • 26,470
  • 12
  • 87
  • 133

1 Answers1

67

After some digging, found it:

query {
  repository(name: "repoName", owner: "repoOwner") {
    object(expression: "branch:path/to/file") {
      ... on Blob {
        text
      }
    }
  }
}

The argument passed to expression on the object field is actually a git revision expression suitable for rev-parse, so I guess you can have fun with it to do advanced querying.

Documentation:

jsta
  • 3,216
  • 25
  • 35
yachaka
  • 5,429
  • 1
  • 23
  • 35
  • 6
    what about binary content with base64 encoded? we have that in v3, but couldn't find a way in v4. – elquimista Nov 29 '17 at 07:18
  • 1
    what's the "..." supposed to be? – SW_user2953243 Jan 14 '19 at 02:34
  • 2
    @SW_user2953243 GraphQL syntax, do not replace the dots – yachaka Jan 15 '19 at 12:40
  • 4
    @SW_user2953243 You are querying for a `GitObject`, which could be a `Blob` (file), but could also be a `Commit`, `Tag` or `Tree`. The `... on Blob` is an [inline fragment](https://graphql.org/learn/queries/#inline-fragments), that allows you to conditionally query for the `text` field if the returned `GitObject` is a `Blob`. – Sam Tolmay Jan 22 '19 at 07:53
  • @SamTolmay I tried same with Tag GitObject but getting empty response. Have any ideas? For invalid tags getting null object. For valid tags only empty json object. { repository(owner: "gradle", name: "gradle") { url object(expression: "v5.3.0") { ... on Tag { oid id } } } } – Furkan Yavuz Mar 26 '19 at 22:32
  • Does not work when the object is a submodule: it returns `object: null`. – mljrg Oct 07 '20 at 22:28