graphql Documentation

An implementation of GraphQL for Go / Golang

10,154 stars Go Go 1 file Β· ~11,988 tokens #graphql#graphql-go#subscriptions
RAW Doc

Docker & Self-Hosted Deployment Verified OCI

Deploy graphql on any server, homelab, or cloud container platform.

1-Click Terminal Command
bash (docker run)
docker run -d --name graphql -p 8910:8910 --restart always postgres:16-bookworm
Configured Services & Ports
βš™οΈ redwood
image: build locally
πŸ”Œ Ports: 8910:8910
βš™οΈ db
image: postgres:16-bookworm
πŸ”Œ Ports: 5432:5432
βš™οΈ console
image: build locally
docker-compose.yml
yaml (docker-compose.yml)
services:
  redwood:
    build:
      context: .
      dockerfile: ./Dockerfile
      target: base
    command: yarn rw dev
    volumes:
      - .:/home/node/app
      - node_modules:/home/node/app/node_modules
    ports:
      - '8910:8910'
    depends_on:
      - db
    environment:
      - DATABASE_URL=postgresql://redwood:redwood@db:5432/redwood
      - TEST_DATABASE_URL=postgresql://redwood:redwood@db:5432/redwood_test
      - SESSION_SECRET=super_secret_session_key_change_me_in_production_please
      - CI=
      - NODE_ENV=development
      - REDWOOD_API_HOST=0.0.0.0

  db:
    image: postgres:16-bookworm
    environment:
      POSTGRES_USER: redwood
      POSTGRES_PASSWORD: redwood
      POSTGRES_DB: redwood
    ports:
      - '5432:5432'
    volumes:
      - postgres:/var/lib/postgresql/data

  # After starting with `docker compose -f ./docker-compose.dev.yml up`,
  # use the console to run commands in the container:
  #
  # ```
  # docker compose -f ./docker-compose.dev.yml run --rm -it console /bin/bash
  # root@...:/home/node/app# yarn rw prisma migrate dev
  # ```
  console:
    user: root
    build:
      context: .
      dockerfile: ./Dockerfile
      target: console
    tmpfs:
      - /tmp
    command: 'true'
    environment:
      - DATABASE_URL=postgresql://redwood:redwood@db:5432/redwood
      - TEST_DATABASE_URL=postgresql://redwood:redwood@db:5432/redwood_test
    depends_on:
      - db

volumes:
  node_modules:
  postgres:

File: README.md

graphql [](https://circleci.com/gh/graphql-go/graphql/tree/master) [](https://pkg.go.dev/github.com/graphql-go/graphql) [](https://coveralls.io/github/graphql-go/graphql?branch=master) [](https://gitter.im/graphql-go/graphql?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

An implementation of GraphQL in Go. Follows the official reference implementation graphql-js.

Supports: queries, mutations & subscriptions.

Documentation

godoc: https://pkg.go.dev/github.com/graphql-go/graphql

Contribute Back

Friendly reminder links are available in case you would like to contribute back into our commitment with Go and open-source.

Author PayPal Link
Hafiz Ismail Not available yet.
Chris RamΓ³n https://www.paypal.com/donate/?hosted_button_id=WHUQQYEMTRQBJ

Getting Started

To install the library, run:

bash
go get github.com/graphql-go/graphql

The following is a simple example which defines a schema with a single hello string-type field and a Resolve method which returns the string world. A GraphQL query is performed against this schema with the resulting output printed in JSON format.

go
package main

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

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

func main() {
	// Schema
	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}
	schemaConfig := graphql.SchemaConfig{Query: graphql.NewObject(rootQuery)}
	schema, err := graphql.NewSchema(schemaConfig)
	if err != nil {
		log.Fatalf("failed to create new schema, error: %v", err)
	}

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

For more complex examples, refer to the examples/ directory and graphql_test.go.

Third Party Libraries

Name Author Description
graphql-go-handler Hafiz Ismail Middleware to handle GraphQL queries through HTTP requests.
graphql-relay-go Hafiz Ismail Lib to construct a graphql-go server supporting react-relay.
golang-relay-starter-kit Hafiz Ismail Barebones starting point for a Relay application with Golang GraphQL server.
dataloader Nick Randall DataLoader implementation in Go.

Blog Posts


File: examples/todo/README.md

Go GraphQL ToDo example

An example that consists of basic core GraphQL queries and mutations.

To run the example navigate to the example directory by using your shell of choice.

text
cd examples/todo

Run the example, it will spawn a GraphQL HTTP endpoint

text
go run main.go

Execute queries via shell.

text
// To get single ToDo item by ID
curl -g 'http://localhost:8080/graphql?query={todo(id:"b"){id,text,done}}'

// To create a ToDo item
curl -g 'http://localhost:8080/graphql?query=mutation+_{createTodo(text:"My+new+todo"){id,text,done}}'

// To get a list of ToDo items
curl -g 'http://localhost:8080/graphql?query={todoList{id,text,done}}'

// To update a ToDo
curl -g 'http://localhost:8080/graphql?query=mutation+_{updateTodo(id:"b",text:"My+new+todo+updated",done:true){id,text,done}}'

Web App

Access the web app at http://localhost:8080/. It is work in progress and currently is simply loading todos by using jQuery ajax call.


File: examples/sql-nullstring/README.md

Go GraphQL SQL null string example

database/sql Nullstring implementation, with JSON marshalling interfaces.

To run the program, go to the directory
cd examples/sql-nullstring

Run the example
go run main.go

sql.NullString

On occasion you will encounter sql fields that are nullable, as in

sql
CREATE TABLE persons (
    id INT PRIMARY KEY,
    name TEXT NOT NULL,
    favorite_dog TEXT -- this field can have a NULL value
)

For the struct

golang
import "database/sql"

type Person struct {
    ID          int             `json:"id" sql:"id"`
    Name        string          `json:"name" sql:"name"`
    FavoriteDog sql.NullString  `json:"favorite_dog" sql:"favorite_dog"`
}

But graphql would render said field as an object {{ false}} or {{Bulldog true}}, depending on their validity.

With this implementation, graphql would render the null items as an empty string (""), but would be saved in the database as NULL, appropriately.

The pattern can be extended to include other database/sql null types.


File: examples/httpdynamic/README.md

Basically, if we have data.json like this:

text
[
  { "id": "1", "name": "Dan" },
  { "id": "2", "name": "Lee" },
  { "id": "3", "name": "Nick" }
]

... and go run main.go, we can query records:

text
$ curl -g 'http://localhost:8080/graphql?query={user(name:"Dan"){id}}'
{"data":{"user":{"id":"1"}}}

... now let's give Dan a surname:

text
[
  { "id": "1", "name": "Dan", "surname": "Jones" },
  { "id": "2", "name": "Lee" },
  { "id": "3", "name": "Nick" }
]

... and kick the server:

text
kill -SIGUSR1 52114

And ask for Dan's surname:

text
$ curl -g 'http://localhost:8080/graphql?query={user(name:"Dan"){id,surname}}'
{"data":{"user":{"id":"1","surname":"Jones"}}}

... or ask Jones's name and ID:

text
$ curl -g 'http://localhost:8080/graphql?query={user(surname:"Jones"){id,name}}'
{"data":{"user":{"id":"1","name":"Dan"}}}

If you look at main.go, the file is not field-aware. That is, all it knows is
how to work with []map[string]string type.

With this, we are not that far from exposing dynamic fields and filters which
fully depend on what we have stored, all without changing our tooling.


File: examples/crud/Readme.md

Go GraphQL CRUD example

Implement create, read, update and delete on Go.

To run the program:

  1. go to the directory: cd examples/crud
  2. Run the example: go run main.go

Create

http://localhost:8080/product?query=mutation+_{create(name:"Inca Kola",info:"Inca Kola is a soft drink that was created in Peru in 1935 by British immigrant Joseph Robinson Lindley using lemon verbena (wiki)",price:1.99){id,name,info,price}}

Read

  • Get single product by id: http://localhost:8080/product?query={product(id:1){name,info,price}}
  • Get product list: http://localhost:8080/product?query={list{id,name,info,price}}

Update

http://localhost:8080/product?query=mutation+_{update(id:1,price:3.95){id,name,info,price}}

Delete

http://localhost:8080/product?query=mutation+_{delete(id:1){id,name,info,price}}