How to Build a GraphQL API in Go

Web
Build a GraphQL API in Go by defining a schema, generating code with gqlgen, implementing resolvers, and running an HTTP server.

Build a GraphQL API in Go by defining your schema, generating code, and wiring handlers to your data source.

package main

import (
	"github.com/99designs/gqlgen/graphql/handler"
	"github.com/99designs/gqlgen/graphql/playground"
	"net/http"
)

func main() {
	h := handler.New(&executableSchema{})
	h.AddTransport(playground.Handler("GraphQL Playground", "/graphql"))
	h.AddTransport(http.NewTransport())
	http.Handle("/graphql", h)
	http.ListenAndServe(":8080", nil)
}
  1. Define your schema in schema.graphql to specify types and queries.
  2. Run go run github.com/99designs/gqlgen generate to create resolvers and executable schema.
  3. Implement resolver logic in resolver.go to fetch data for your queries.
  4. Start the server with http.ListenAndServe to expose the /graphql endpoint.