Prerequisites

Before we start, ensure you have the following:

  • Go installed on your machine (version 1.16 or higher).
  • Basic understanding of Go programming.
  • Familiarity with GraphQL concepts.

Project Setup

  1. Create a new directory for your project:
   mkdir go-graphql-api
   cd go-graphql-api
  1. Initialize a Go module:
   go mod init go-graphql-api
  1. Install the necessary packages:

We will use the graphql-go library for handling GraphQL queries.

   go get github.com/graphql-go/graphql

Define Your Data Model

For this tutorial, we will create a simple API that manages a list of books. Each book will have a title, author, and publication year.

package main

type Book struct {
    ID     string
    Title  string
    Author string
    Year   int
}

// Sample data
var books = []Book{
    {ID: "1", Title: "1984", Author: "George Orwell", Year: 1949},
    {ID: "2", Title: "Brave New World", Author: "Aldous Huxley", Year: 1932},
    {ID: "3", Title: "Fahrenheit 451", Author: "Ray Bradbury", Year: 1953},
}

Define the GraphQL Schema

Next, we will define the GraphQL schema that represents our data model and the queries we can perform.

package main

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

// Define the GraphQL object type for Book
var bookType = graphql.NewObject(graphql.ObjectConfig{
    Name: "Book",
    Fields: graphql.Fields{
        "id":     &graphql.Field{Type: graphql.String},
        "title":  &graphql.Field{Type: graphql.String},
        "author": &graphql.Field{Type: graphql.String},
        "year":   &graphql.Field{Type: graphql.Int},
    },
})

// Define the root query
var rootQuery = graphql.NewObject(graphql.ObjectConfig{
    Name: "RootQuery",
    Fields: graphql.Fields{
        "books": &graphql.Field{
            Type: graphql.NewList(bookType),
            Resolve: func(params graphql.ResolveParams) (interface{}, error) {
                return books, nil
            },
        },
        "book": &graphql.Field{
            Type: bookType,
            Args: graphql.FieldConfigArgument{
                "id": &graphql.ArgumentConfig{
                    Type: graphql.NewNonNull(graphql.String),
                },
            },
            Resolve: func(params graphql.ResolveParams) (interface{}, error) {
                id := params.Args["id"].(string)
                for _, book := range books {
                    if book.ID == id {
                        return book, nil
                    }
                }
                return nil, nil
            },
        },
    },
})

// Create the schema
var schema, _ = graphql.NewSchema(graphql.SchemaConfig{
    Query: rootQuery,
})

Implement the GraphQL Server

Now that we have defined our schema, we can implement a simple HTTP server to handle GraphQL requests.

package main

import (
    "net/http"
    "github.com/graphql-go/handler"
)

func main() {
    // Create a new GraphQL handler
    h := handler.New(&handler.Config{
        Schema: &schema,
        Pretty: true,
        GraphiQL: true, // Enable GraphiQL interface
    })

    // Set up the HTTP server
    http.Handle("/graphql", h)
    http.ListenAndServe(":8080", nil)
}

Testing the API

To test the API, run the server:

go run main.go

Open your browser and navigate to http://localhost:8080/graphql. You will see the GraphiQL interface, which allows you to interact with your GraphQL API.

Example Queries

  1. Fetch all books:
   {
       books {
           id
           title
           author
           year
       }
   }
  1. Fetch a single book by ID:
   {
       book(id: "1") {
           title
           author
       }
   }

Summary

In this tutorial, we built a simple GraphQL API using Go. We defined a data model, created a GraphQL schema, and set up an HTTP server to handle requests. This foundational knowledge can be expanded upon to create more complex APIs, including mutations and subscriptions.

FeatureDescription
LanguageGo
Librarygraphql-go
Data ModelBooks with ID, Title, Author, Year
Server TypeHTTP with GraphiQL interface
Query ExampleFetch all books or a single book by ID

Learn more with useful resources