Skip to content
Getting started

Getting started

Install

go get github.com/gql-go/graphql

The library requires Go 1.27 or newer. If you cannot upgrade Go yet, use v0.9.x, which builds with Go 1.21 and receives security fixes for the period stated in the security policy.

A first schema

The program below defines a schema with a single hello field and runs a query against it.

package main

import (
	"encoding/json"
	"fmt"
	"log"

	"github.com/gql-go/graphql"
)

func main() {
	fields := graphql.Fields{
		"hello": &graphql.Field{
			Type: graphql.String,
			Resolve: func(p graphql.ResolveParams) (interface{}, error) {
				return "world", nil
			},
		},
	}
	rootQuery := graphql.ObjectConfig{Name: "RootQuery", Fields: fields}
	schema, err := graphql.NewSchema(graphql.SchemaConfig{Query: graphql.NewObject(rootQuery)})
	if err != nil {
		log.Fatalf("failed to create schema: %v", err)
	}

	r := graphql.Do(graphql.Params{Schema: schema, RequestString: `{ hello }`})
	if len(r.Errors) > 0 {
		log.Fatalf("failed to execute operation: %+v", r.Errors)
	}
	rJSON, _ := json.Marshal(r)
	fmt.Printf("%s\n", rJSON)
}

Running it prints:

{"data":{"hello":"world"}}

graphql.Do parses, validates and executes the request in one call. Errors in the request, such as a field that does not exist, are returned in r.Errors together with any partial r.Data, as the specification requires; they are not Go errors.

Coming from graphql-go/graphql

The package name and the API are unchanged; only the module path is different. Replace the import prefix across your code:

github.com/graphql-go/graphql  ->  github.com/gql-go/graphql

Migrating from graphql-go has the full steps, including the handler and the Go version.

Next steps

  • The examples/ directory has complete programs: CRUD, context, concurrent resolvers, custom scalars, HTTP servers and more.
  • To serve the schema over HTTP, see gql-go/handler.
  • The API reference documents every type and function.
Last updated on