GraphQL API Integration on a Golang Project
There are many GraphQL client written in golang. machinebox/graphql
is a Low-level GraphQL client for Go.
This client is,
- Simple, familiar API
- Respects context.Context timeouts and cancellation
- Build and execute any kind of GraphQL request
- Use strong Go types for response data
- Use variables and upload files
- Simple error handling
Installation
Make sure you have a working Go environment. To install graphql, simply run:
$ go get github.com/machinebox/graphql
Usage
note
Always remember to replace API_SECRET
with the correct value that you copied from apito console.
Go to this page if you do not know where to find your api secrets for your project
import "context"
// create a client (safe to share across requests)
client := graphql.NewClient("https://api.apito.io/secured/graphql")
// make a request
req := graphql.NewRequest(`
query ($key: String!) {
items (id:$key) {
field1
field2
field3
}
}
`)
// set any variables
req.Var("key", "value")
// set header fields
req.Header.Set("Authorization", "Bearer API_SECRET")
// define a Context for the request
ctx := context.Background()
// run it and capture the response
var respData ResponseStruct
if err := client.Run(ctx, req, &respData); err != nil {
log.Fatal(err)
}