Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by disabling your ad blocker.

Interacting with a GraphQL API with Golang

TwitterFacebookRedditLinkedInHacker News

You might remember that I’ve done quite a bit of content when it comes to developing GraphQL APIs with the Go programming language (Golang). Heck, I’ve even written a book and published a course on the subject. However, in everything I’ve done thus far, I haven’t demonstrated how to interact with a GraphQL using Golang.

Sure, a lot of the time you’ll be using something like React, Angular, or Vue to interact with your web service, but that doesn’t mean you’ll never need to query a GraphQL API from Go or execute a mutation.

In this tutorial we’re going to see some quick examples on how to make HTTP requests with GraphQL queries using Golang.

Before we get too far into the tutorial, I want to make the assumption that you’ve already created or found a GraphQL API to use. This tutorial won’t demonstrate how to actually create a GraphQL API with Golang. We’re only going to be interacting with an existing API.

Querying a GraphQL API with the Golang HTTP Package

Because GraphQL is typically interacted with over HTTP, we can leverage packages that already exist within Go, particularly the net/http package, which is quite powerful.

Take the following code for example:

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
    "time"
)

func main() {
    jsonData := map[string]string{
        "query": `
            { 
                people {
                    firstname,
                    lastname,
                    website
                }
            }
        `,
    }
    jsonValue, _ := json.Marshal(jsonData)
    request, err := http.NewRequest("POST", "https://<GRAPHQL_API_HERE>", bytes.NewBuffer(jsonValue))
    client := &http.Client{Timeout: time.Second * 10}
    response, err := client.Do(request)
    defer response.Body.Close()
    if err != nil {
        fmt.Printf("The HTTP request failed with error %s\n", err)
    }
    data, _ := ioutil.ReadAll(response.Body)
    fmt.Println(string(data))
}

In the main function we are defining the query. In most GraphQL implementations, the API expects POST requests with a query field in the payload. We could easily create a data structure to represent this, but we can just as easily use a map in Go.

For this example, we’re assuming there is a GraphQL people query in the schema and each of the firstname, lastname, and website fields exist in that schema.

We need to send this GraphQL query as JSON, so we marshal it into bytes that we can send with a POST request. After executing the request, we can look at the Body of the response which contains the results of our query.

More information on making HTTP requests in Golang can be found in my previous tutorial titled, Consume RESTful API Endpoints within a Golang Application.

Instead of a query, a GraphQL mutation can be created using the same approach.

Leveraging a Third-Party Package to Work with GraphQL in Golang

Dealing with the net/http commands that ship with Golang might not be the most desireable when it comes to GraphQL. Even though they work, I personally don’t find writing GraphQL queries to be elegant with them.

Instead, it might make sense to use an available community contributed GraphQL package to make our requests. Take the graphql client for example.

To install this package, execute the following with the command line:

go get github.com/machinebox/graphql

Now that our client is available, we can alter our project code to look like the following:

package main

import (
    "context"
    "fmt"

    "github.com/machinebox/graphql"
)

func main() {
    graphqlClient := graphql.NewClient("https://<GRAPHQL_API_HERE>")
    graphqlRequest := graphql.NewRequest(`
        {
            people {
                firstname,
                lastname,
                website
            }
        }
    `)
    var graphqlResponse interface{}
    if err := graphqlClient.Run(context.Background(), graphqlRequest, &graphqlResponse); err != nil {
        panic(err)
    }
    fmt.Println(graphqlResponse)
}

The results of the graphql package should be quite similar in format to the results from the basic Go HTTP request. You can learn about adding header information or additional parameters in the documentation.

Conclusion

You just saw two options when it comes to consuming GraphQL APIs from the Go programming language (Golang). This is different from my previous examples which focused on developing the GraphQL rather than interacting with the GraphQL API.

If you’re interested in learning more about GraphQL and Golang, I strongly encourage you to check out my course, Web Services for the Go Developer, as it is quite thorough and will get you started in the right direction when it comes to web services.

A video version of this tutorial can be seen below.

Nic Raboy

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in C#, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Unity. Nic writes about his development experiences related to making web and mobile development easier to understand.