How to implement a GraphQL Server in Golang using the Schema-First Approach

GraphQL Server in Golang

This is the Golang version of the article — Building GraphQL Server Using Schema-first Approach in Python.

Exploring the Golang GraphQL server with CRUD operations

It uses the exact same schema implementations in Golang.

The schema-first approach means we will write our schema first, using the GraphQL schema definition language. In the code-first approach, we will construct our schema using the library APIs.

We will be using gqlgen as our schema-first GraphQL library for Golang.

Overview of the Project

We are going to build the GraphQL server that handles the CRUD operation of Book in the Book Store.

Simply, we will be storing the book’s information in our database. To simplify this project, I haven’t used any kind of database; I just used an in-memory store and focused more on the GraphQL part.

Server Operations

  • Add books
  • Get book by ID
  • List books by genre
  • List all the books
  • Update the book
  • Delete the book

Building the GraphQL Server with Golang

Getting started

  • Let’s create our project dir.
  • Initialize the Go module with go mod init <dirname>.


  • Get our package by go get
  • Initialize gqlgen by go run init
  • run go mod tidy to get the required packages
Go module
gqlgen init

At this point, we could see various files and folders under the directory graphql. The directory graph was generated by gqlgen after we typed the init command.

Generate files

model/model_gen.go — this is a file with structs generated by gqlgen and defined by the schema file schema.graphqls

generated/generated.go — this is a file with generated code that injects context and middleware for each query and mutation.

You should not modify either of those files since they will be modified by gqlgen as we update our schema and generate.

graph/resolver.go — is the root graph resolver type. This file won’t get regenerated. This is the file where we declare our app’s dependencies, like our database.

schema.graphqls — is a GraphQL schema file that defines types, queries, and mutations. The schema file uses schema-definition-language (SDL) to describe data types and operations (queries/mutations) in a human-readable way.

schema.resolvers.go — is a Go file with wrapper code for queries and mutations defined in schema.graphqls

Defining our GraphQL Schema

I invite you to define the schema and implement the code in your own way and requirement.