Go GraphQL: Setting up GraphQL Server & Schema in Golang #2

In this post, we will set up GraphQL project & basic GraphQL server for our GraphQL API



In this section, you will set up the project for your GraphQL server and implement your first GraphQL query. In the end, we’ll talk about theory for a bit and learn about the GraphQL schema.
. . .

Creating the project

This tutorial teaches you how to build a GraphQL server from scratch, so the first thing you need to do is create the directory that’ll hold the files for your GraphQL server!
Open your terminal, navigate to the golang src folder and run the following commands:
mkdir go-graphql-swapi
cd go-graphql-swapi
glide init

Note This tutorial uses glide to manage your project dependencies. If you dont have glide installed already get from here

This creates a new directory called go-graphql-swapi and initializes it with a glide.yaml file. glide.yaml is the file that contains the list of modules on which our project is dependent.
. . .

Creating GraphQL server

With the project directory in place, you can go ahead and create the entry point for your GraphQL server. This will be a file called main.go, located inside the go-graphql-swapi directory.
In your terminal, first go to go-graphql-swapi directory and then the run below command to create empty main.go file:
touch main.go

To start the app, you can now execute go run main.go inside the go-graphql-swapi directory. At the moment, this won’t do anything because index.js is still empty ¯\_(ツ)_/¯

Let’s go and start building the GraphQL server! The first thing you need to is - surprise - add a dependency to the project.
Run the following command in your terminal:
glide get github.com/graphql-go/graphql glide get github.com/graphql-go/handler

graphql-go/graphql is a fully-featured GraphQL server. It is based on Express.js and a few other libraries to help you build production-ready GraphQL servers.

Here’s a list of its features:
  • GraphQL spec-compliant
  • Realtime functionality with GraphQL subscriptions
  • Out-of-the-box support for GraphQL Playground
  • Resolves custom directives in your GraphQL schema

Perfect, it’s time to write some code 🙌
Open main.go and type the following:

package main

import (
"fmt"
"net/http"

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

func main() {

// 1
queryType := graphql.NewObject(graphql.ObjectConfig{
Name: "Query",
Fields: graphql.Fields{
// 2
"hello": &graphql.Field{
Type: graphql.String,
// 3
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
return "world", nil
},
},
},
})

// 4
Schema, err := graphql.NewSchema(graphql.SchemaConfig{
Query: queryType,
})
if err != nil {
// panic if there is an error in schema
panic(err)
}

// 5
h := handler.New(&handler.Config{
Schema: &Schema,
Pretty: true,
})

// static file server to serve Graphiql in-browser editor
fs := http.FileServer(http.Dir("static"))
http.Handle("/", fs)

// graphql api server
http.Handle("/graphql", h)

fmt.Println("server is started at: http://localhost:8080/")
fmt.Println("graphql api server is started at: http://localhost:8080/graphql")
http.ListenAndServe(":8080", nil)
}
All right, let’s understand what’s going on here by walking through the numbered comments:
  1. Creates the root query which contains our graphql queries and their resolvers, which is passed to the main graphql handler
  2. It defines a simple Query type with one field called hello. This field has the type String
  3. The resolvers object is the actual implementation of the GraphQL schema. which resolvers the hello query and returns the 'world' string
  4. A combined schema is created which contains the root query.
  5. Finally, the schema and resolvers are bundled and passed to the GraphQLServer This tells the server what API operations are accepted and how they should be resolved.

static dir contains the code to render the GraphQL playground. Get the code from here and put it inside the /static/index.html
Go ahead and test your GraphQL server!
. . .

Testing the GraphQL server

In the root directory of your project, run the following command:
go run main.go

As indicated by the terminal output, the server is now running on http://localhost:8080. To test the API of your server, open a browser and navigate to that URL.

What you’ll then see is a GraphQL Playground, a powerful “GraphQL IDE” that lets you explore the capabilities of your API in an interactive manner.

By clicking the DOCS-button on the right, you can open the API documentation. This documentation is auto-generated based on your schema definition and displays all API operations and data types of your schema.

Let’s go and send your very first GraphQL query. Type the following into the editor pane on the left side:
query {
hello
}

Now send the query to the server by clicking the Play-button in the center (or use the keyboard shortcut CMD+ENTER for Mac and CTRL+ENTER on Windows and Linux).

Congratulations, you just implemented and successfully tested your first GraphQL query 🎉
. . .

A word on the GraphQL schema

At the core of every GraphQL API, there is a GraphQL schema. So, let’s quickly talk about it.
Note: In this tutorial, we’ll only scratch the surface of this topic. If you want to go a bit more in-depth and learn more about the GraphQL schema as well as its role in a GraphQL API, be sure to check out this excellent article.

GraphQL schemas are usually written in the GraphQL Schema Definition Language (SDL). The SDL has a type system that allows defining data structures (just like other strongly typed programming languages such as Java, TypeScript, Swift, Go, …).
. . .
In the next tutorial, we will be extending our schema & will add more queries to GraphQL API.



Never miss a post from Gufran Mirza, when you sign up for Ednsquare.