Introducing genqlient: A Type-Safe Go GraphQL Client
What is genqlient?
genqlient is a Go library designed to simplify the interaction with GraphQL APIs by automatically generating type-safe code. Leveraging the strongly-typed nature of both GraphQL and Go, genqlient ensures that your code makes valid GraphQL queries and utilizes the results correctly, reducing the chance of runtime errors and minimizing boilerplate code.
Key Features of genqlient
-
Compile-Time Query Validation: genqlient checks your GraphQL queries at compile-time, ensuring you never deploy a malformed query.
-
Type-Safe Response Objects: It generates appropriate Go types for each query, providing a smooth unmarshalling process without resorting to generic
interface{}
types. -
Production-Ready: Trusted in production at Khan Academy, genqlient efficiently supports a vast number of learners and educators worldwide.
How to Use genqlient?
To incorporate genqlient into your Go project, you can run it with a simple command: go run github.com/Khan/genqlient
. For setting up your project, refer to the getting started guide or explore the examples. For comprehensive documentation, check out the docs.
Contributing to genqlient
genqlient is an open-source project that welcomes contributions. Those interested can consult the Contribution Guidelines or submit an issue on GitHub.
Why Choose genqlient Over Other GraphQL Clients?
Traditional Go GraphQL clients often require developers to manually code queries and accompanying response structures. Consider this example:
query := `query GetUser($id: ID!) { user(id: $id) { name } }`
variables := map[string]interface{}{"id": "123"}
var resp struct {
Me struct {
Name graphql.String
}
}
client.Query(ctx, query, &resp, variables)
fmt.Println(resp.Me.Name)
// Output: Luke Skywalker
While functional, this approach has several drawbacks:
-
Schema Assurance: The Go struct is not automatically validated against the GraphQL schema. Mistakes in field names or capitalization might surface only during runtime.
-
Type Safety of Variables: GraphQL variables lack type safety. For instance, providing
{"id": true}
would not trigger an error until execution. -
Repetitive Code: The necessity to define types for queries and responses creates code redundancy or involves hiding queries within complex struct tags, diminishing any available type safety.
These problems, although manageable in straightforward applications, can hinder production-grade projects. Given that GraphQL and Go are typed languages and GraphQL schemas are publicly available in a machine-readable format, there is potential for automatic validation and type generation.
genqlient bridges this gap by allowing developers to specify the query, after which it generates type-safe helpers validated against the schema, easing the process of querying and responding.