Query resources with NerdGraph, New Relic's GraphQL API

newrelicgraphqlgolang

NerdGraph is New Relic’s GraphQL API and it can be used for querying resources or migrating it.

curl -X POST https://api.newrelic.com/graphql \
-H 'Content-Type: application/json' \
-H 'API-Key: *****' \
-d '{ "query":  "{ requestContext { userId apiKey } actor { user { name } } }" }' | jq
{
  "data": {
    "actor": {
      "user": {
        "name": "Taiki Sakamoto"
      }
    },
    "requestContext": {
      "apiKey": "*****",
      "userId": "*****"
    }
  }
}

If select resources in GraphiQL explorer, the query is generated.

It can be also executed from the client library. Structs are auto generated by tutone with GraphQL schema introspection and template.

package main

import (
	"context"
	"fmt"
	"logging"
	"os"

	"github.com/newrelic/newrelic-client-go/newrelic"
	"github.com/newrelic/newrelic-client-go/pkg/users"
)

func main() {
	// Initialize the client.
	client, err := newrelic.New(newrelic.ConfigPersonalAPIKey(os.Getenv("NEW_RELIC_API_KEY")))
	if err != nil {
		log.Fatal("error initializing client:", err)
	}
	query := `
	query($queryName: String!) {
		actor {
			users {
				userSearch(query: {scope: {name: $queryName}}) {
					users {
						id
						email
						name
					}
				}
			}
		}
	}
	`
	var resp struct {
		Actor struct {
			Users struct {
				UserSearch struct {
					Users []users.User
				}
			}
		}
	}
	variables := map[string]interface{}{
		"queryName": "Sakamoto",
	}
	if err := client.NerdGraph.QueryWithResponseAndContext(context.TODO(), query, variables, &resp); err != nil {
		log.Fatal("error query:", err)
	}
	fmt.Println(resp.Actor.Users.UserSearch.Users[0].Name) // => Taiki Sakamoto
}