Table of Contents
- Introduction
- Prerequisites
- Setup
- Creating the GraphQL Schema
- Implementing the Resolvers
- Running the GraphQL Server
- Conclusion
Introduction
In this tutorial, you will learn how to implement a GraphQL API in Go. GraphQL is a query language for APIs and a runtime for executing those queries with your existing data. By the end of this tutorial, you will be able to create a basic GraphQL API with Go and understand the fundamental concepts behind it.
Prerequisites
To follow along with this tutorial, you should have basic knowledge of Go programming language. You should also have Go installed on your machine. If you haven’t installed Go, please visit the official Go website and follow the installation instructions for your operating system.
Setup
-
Create a new directory for your project and navigate to it using the command line.
-
Initialize a new Go module by running the following command:
```shell go mod init github.com/your-username/your-project-name ``` Replace `github.com/your-username/your-project-name` with your desired module path.
-
Install the necessary dependencies by executing the following commands:
```shell go get github.com/graphql-go/graphql go get github.com/graphql-go/handler ``` These commands will download and install the GraphQL packages required for our project.
Creating the GraphQL Schema
The first step in implementing a GraphQL API is defining the schema. The schema defines the types and operations available in your API. Create a new file called schema.go
and add the following code:
package main
import "github.com/graphql-go/graphql"
var RootQuery = graphql.NewObject(
graphql.ObjectConfig{
Name: "RootQuery",
Fields: graphql.Fields{
"hello": &graphql.Field{
Type: graphql.String,
Resolve: func(params graphql.ResolveParams) (interface{}, error) {
return "Hello, world!", nil
},
},
},
},
)
var Schema, _ = graphql.NewSchema(
graphql.SchemaConfig{
Query: RootQuery,
},
)
In the code above, we define a single query field called “hello” which returns a String
type. The resolver function for this field simply returns the string “Hello, world!”.
Implementing the Resolvers
The resolvers are responsible for fetching the data for each field in the schema. Create another file called resolvers.go
and add the following code:
package main
type Resolver struct{}
func (r *Resolver) Hello(params graphql.ResolveParams) (interface{}, error) {
return "Hello, world!", nil
}
In the code above, we define a struct Resolver
which contains the resolver functions for each field. In this case, we only have one resolver for the “hello” field, which returns the string “Hello, world!”.
Running the GraphQL Server
Now that we have our schema and resolvers defined, we can create the GraphQL server. Create a new file called main.go
and add the following code:
package main
import (
"encoding/json"
"net/http"
"github.com/graphql-go/graphql"
"github.com/graphql-go/handler"
)
func mainHandler(schema graphql.Schema) http.HandlerFunc {
h := handler.New(&handler.Config{
Schema: &schema,
Pretty: true,
GraphiQL: true,
})
return func(w http.ResponseWriter, r *http.Request) {
h.ServeHTTP(w, r)
}
}
func main() {
http.HandleFunc("/graphql", mainHandler(Schema))
http.ListenAndServe(":8080", nil)
}
In the code above, we create an HTTP handler function mainHandler
that serves our GraphQL API. We use the github.com/graphql-go/handler
package to handle the GraphQL queries and provide a GraphiQL interface for testing. The server listens on port 8080 for incoming requests.
To start the GraphQL server, run the following command in your project directory:
go run main.go
You should see the server starting message in the console.
Conclusion
Congratulations! You have successfully implemented a basic GraphQL API in Go. You learned how to define the schema, implement the resolvers, and run the GraphQL server. This is just the beginning, and there is much more you can do with GraphQL and Go. Continue exploring the documentation and experimenting with more complex schemas and resolvers to build powerful APIs.
I hope you found this tutorial helpful and that it serves as a good starting point for your GraphQL journey in Go. Happy coding!