Fetching Github Blame with the GraphQL API V4

March 14, 2018

Github API V3 was REST; V4 is GraphQL.

Below you'll find a code snippet that fetches Github blame.

let owner = 'facebook'
let name = 'react'
let path = 'packages/react/index.js'
let token = 'MY_PERSONAL_GITHUB_TOKEN'
fetch('https://api.github.com/graphql', {
  method: 'POST',
  headers: {
    'Authorization': `bearer ${token}`    
  },
  body: JSON.stringify({
    query: `query {
      repository(owner:\"${owner}\", name:\"${name}\") {
        defaultBranchRef {
          target {
            ... on Commit {
              blame(path: \"${path}\") {
                ranges {
                  startingLine
                  endingLine
                  age
                  commit {
                    id
                    commitUrl
                    commitResourcePath
                    committedDate
                    message
                    messageBody
                    oid
                    url
                  }
                }
              }
            }
          }
        }
      }
    }`
  })
}).then(resp => resp.json())
  .then(resp => {
  console.log(resp)
})