Skip to content

An Intro to GitHub GraphQL API

How to Use GraphQL API with PowerShell – A GitHub Example

In my work on a recent customer project, I came across the need to make a GraphQL API call with PowerShell to query and set branch protection rules on a repository in GitHub. I couldn’t find a suitable solution, so I wrote this blog for other software engineers with similar queries.

Getting Started with GraphQL

GraphQL is a query language for APIs that isn’t tied to a specific database or storage engine. It’s backed by existing code and data and acts as a server-side runtime for executing queries using a system type defined for data. More so, you can use GraphQL to create an API with custom types that can be queried, similar to how REST API calls are made.

GitHub GraphQL API

The GitHub GraphQL API has definitions for queries and mutations, which are used to define the API calls we will be making. We will first demonstrate the authentication required, followed by an example query and mutation API call. Whether a query or mutation operation, an endpoint URL and body are necessary for the call.

Forming an Authentication Header

Before sending a GraphQL API call, we must form our authentication header using a GitHub personal access token (PAT). Let’s set our GitHub PAT as an environment variable on PowerShell command line so that when we run our code, the authentication headers form correctly.

$env:GitHubPat = "{GitHub PAT}"Code language: PowerShell (powershell)

This PAT comes into play when authenticating to the GitHub organization and repository we specify. Let’s set those local values to variables in our query example.

$RepoName = "BlogSamples"
$Org = "IntelliTect-Samples"
Code language: PowerShell (powershell)

With this PAT set, we can form the headers by defining and calling our Get-Headers function.

function Get-Headers {
    param(
        [Parameter (Mandatory = $TRUE)]
        $GitHubPat
    )
    $headers = @{'Authorization' = "Bearer $GitHubPat" }
    return $headers
}
$Headers = Get-Headers $env:GitHubPat
Code language: PowerShell (powershell)

Query Example

The below GraphQL API call demonstrates the endpoint URL and body for querying the branch protection rules. The code below shows the multiple parts of the body, including the query, operationName, and variables.

$Url = "https://api.github.com/graphql"
    $Body = @{ `
        query = "query GetBranchProtectionRules(`$org: String!, `$repo: String!, `$number_of_rules:Int!) { `
                    repository(owner: `$org, name: `$repo) { `
                            branchProtectionRules(last: `$number_of_rules) { `
                                edges { `
                                    node { `
                                        id `
                                        pattern `
                                        isAdminEnforced `
                                        allowsDeletions `
                                        requiresStatusChecks `
                                        requiresStrictStatusChecks `
                                        dismissesStaleReviews `
                                        restrictsReviewDismissals `
                                        requiredApprovingReviewCount `
                                    } `
                                } `
                            } `
                        } `
                    }"
        operationName = "GetBranchProtectionRules"
        variables = ConvertTo-Json @{ "org" = $Org
                                        "repo" = $RepoName
                                        "number_of_rules" = 4}
    }

    $Body = $Body | ConvertTo-Json
Code language: PowerShell (powershell)

 The query portion of the body defines the type of operation performed, which in our case, is a query. This query operation type is separate from the query object defined in the body. Specifically, we have named our query operation GetBranchProtectionRules (referenced as the operation performed in the second item in the body). It is important to note that defining our named query operation GetBranchProtectionRules is optional instead of simply writing the operation in plain text. A key advantage to this named operation is the ability to pass in variable values from the PowerShell script.

Another critical point to note is how the desired branch protection rule properties were determined to be defined as part of the GetBranchProtectionRules query operation. On the GitHub GraphQL documentation for queries, there is a definition for the repository type, which contains the subsequent property BranchProtectionRules of type BranchProtectionRuleConnection. Connection objects within the GitHub GraphQL API include an edges property containing a node property. In our example above, the node is an individual BranchProtectionRule with its own properties. We select eight properties to return within the node for each branch protection rule.

Finally, we make the API call and parse the response.

$Body = $Body | ConvertTo-Json
$Result = Invoke-RestMethod -Method 'Post' -Uri $Url -Body $Body -Headers $Headers
$Rules = $Result.data.repository.branchProtectionRules.edges.node
Code language: PowerShell (powershell)

As you can see, we use Invoke-RestMethod to make our API call. To retrieve our branch protection rules as a PowerShell object, we must select the object according to the hierarchy of properties specified in our request’s body.

Now, on the command line, we can print out the value of $Rules from our sample repository, which has previously created branch protection rules.

graphql api

Mutation Example

To modify or delete an object within GitHub, you need to specify a mutation type in the body of the request. For our example, we are using the mutation type deleteBranchProtectionRule.

$Rule = $Rules[0]
$Url = "https://api.github.com/graphql"
$Id = $Rule.id
$Pattern = $Rule.pattern
Write-Information "Deleting branch protection rule"
$Body = @{
    query = "mutation {
        deleteBranchProtectionRule(input:{branchProtectionRuleId: `"$Id`"}) {
        clientMutationId
         }
    }"
}

$Body = $Body | ConvertTo-Json
$Result = Invoke-RestMethod -Method 'Post' -Uri $Url -Body $Body -Headers $Headers
Code language: PowerShell (powershell)

The body for this mutation is more straightforward and only contains the query. The query portion of the body again defines the type of operation to occur (mutation). Then, the mutation is specified as deleteBranchProtectionRule which takes in the input of type deleteBranchProtectionRuleInput. This input is an object with one required property, branchProtectionRuleId, that must be defined. In our sample, you can see how our predefined branch protection rule Id is passed into the body of our request. After building up the body and converting it to JSON, we can use Invoke-RestMethod to retrieve the result of the operation.

if(!$Result.error)
{
    Write-Information "Success: deleted branch protection rule $Pattern"
}
Code language: PowerShell (powershell)

Wrapping Up

To summarize, we have demonstrated two sample GraphQL API callsa query and a mutation. These samples will hopefully help you on your development journey and add to your personal PowerShell experience.

Want More?

Looking to use PowerShell to interact with an Oracle database? Check out QA Architect Mike Curn’s blog on data-fetching from Oracle SQL using PowerShell. To learn about other coding technologies, check out our tech blog and developer tools!

Does Your Organization Need a Custom Solution?

Let’s chat about how we can help you achieve excellence on your next project!