GraphQL is a powerful query language for APIs that allows clients to request exactly the data they need and nothing more. Go, on the other hand, is a fast and efficient programming language that has gained popularity in recent years for building web applications and APIs. In this tutorial, we will explore how to create GraphQL APIs with Go programming using the popular library, gqlgen.


Prerequisites

Before we get started, make sure you have the following installed on your machine:

  • Go (version 1.16 or higher)
  • gqlgen

You can install gqlgen using the following command:


Setting up the Project

First, create a new directory for your project and navigate to it in your terminal. Then, initialize a new Go module using the following command:

go mod init <module-name>

Replace <module-name> with the name of your module.

Next, create a new file called schema.graphqls in your project directory. This file will define the schema for your GraphQL API.

Here's an example schema:

type Query {
  hello: String!
}

This schema defines a single query called hello, which returns a string.


Generating Code with gqlgen

Now that we have defined our schema, we can use gqlgen to generate the necessary Go code to implement our API.

Run the following command in your terminal to generate the code:

go run github.com/99designs/gqlgen generate

This will create a new file called generated.go in your project directory. This file contains the code for your GraphQL API, including resolvers for your queries and mutations.


Implementing the Resolvers

Now that we have generated the code for our GraphQL API, we need to implement the resolvers for our queries.

Open the resolver.go file in your project directory. This file contains the template for your resolvers.

Here's an example resolver for our hello query:

package graph

import (
  "context"
)

type Resolver struct{}

func (r *Resolver) Hello(ctx context.Context) (string, error) {
  return "world", nil
}

This resolver simply returns the string "world" in response to the hello query.


Starting the Server

Now that we have implemented our resolvers, we can start the GraphQL server.

Open the server.go file in your project directory. This file contains the code for starting the server.

Here's an example server.go file:

package main

import (
  "log"
  "net/http"

  "github.com/99designs/gqlgen/handler"
  "github.com/gorilla/mux"
  "github.com/rs/cors"

  "path/to/generated"
)

func main() {
  r := mux.NewRouter()

  // Add the GraphQL API handler to the router
  r.Handle("/graphql", handler.GraphQL(generated.NewExecutableSchema(generated.Config{Resolvers: &generated.Resolver{}})))

  // Add a playground for testing the GraphQL API
  r.Handle("/playground", handler.Playground("GraphQL playground", "/graphql"))

  // Use CORS middleware to allow cross-origin requests
  handler := cors.Default().Handler(r)

  // Start the server
  log.Printf("connect to http://localhost:8080/playground for GraphQL playground")
  log.Fatal(http.ListenAndServe(":8080", handler))
}

This file sets up a new router using the Gorilla mux package and adds the GraphQL API handler and playground endpoints. It also uses the rs/cors package to enable cross-origin requests.

Finally, it starts the server on port 8080 and logs a message to the console indicating that the server is running.


Testing the API

Now that we have implemented our resolvers and started the server, we can test our GraphQL API using the playground.

To access the playground, navigate to http://localhost:8080/playground in your web browser.

In the left panel of the playground, you will see the documentation for your GraphQL API. In the right panel, you can enter queries to test your API.

For example, to test our hello query, enter the following query in the right panel:

query {
  hello
}

Click the "play" button to execute the query. You should see the following response:

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

Congratulations! You have successfully created a GraphQL API with Go programming.


Conclusion

In this tutorial, we have explored how to create GraphQL APIs with Go programming using the gqlgen library. We started by defining our schema, then used gqlgen to generate the necessary Go code. We then implemented our resolvers and started the server. Finally, we tested our API using the playground.

GraphQL is a powerful tool for building APIs, and Go is a fast and efficient programming language that is well-suited for building web applications and APIs. By combining these two technologies, we can create robust and scalable APIs that can handle complex queries and mutations.