Skip to content

Using the CoCore API from Go

To assist Go developers in integrating with the CoCore GraphQL API, here's a comprehensive guide utilizing the go-graphql-client library.

1. Install the go-graphql-client Library

Begin by installing the go-graphql-client package:

bash
go get -u github.com/hasura/go-graphql-client

2. Initialize the GraphQL Client

Create an instance of the GraphQL client, specifying your CoCore GraphQL endpoint:

go
package main

import (
	"context"
	"net/http"

	"github.com/hasura/go-graphql-client"
)

func main() {
	client := graphql.NewClient("$MY_COCORE_URL/graphql", http.DefaultClient)
	// Use the client...
}

3. Authenticate Requests

Include the API key in the client by modifying the request headers. You can generate an API key from the settings menu in your CoCore instance:

go
client := graphql.NewClient("$MY_COCORE_URL/graphql", http.DefaultClient).
	WithRequestModifier(func(r *http.Request) {
		r.Header.Set("Authorization", "Bearer YOUR_API_KEY")
	})

4. Define GraphQL Queries

Construct your GraphQL queries by defining corresponding Go structs. Here's an example of a query to fetch job information:

go
package main

import (
	"context"
	"fmt"
	"net/http"

	"github.com/hasura/go-graphql-client"
)

type Job struct {
	ID       string
	Name     string
	Quantity int
}

func main() {
	client := graphql.NewClient("$MY_COCORE_URL/graphql", http.DefaultClient).
		WithRequestModifier(func(r *http.Request) {
			r.Header.Set("Authorization", "Bearer YOUR_API_KEY")
		})

	var query struct {
		Job Job `graphql:"job(id: $id)"`
	}
	variables := map[string]interface{}{
		"id": graphql.ID("job-id"),
	}

	err := client.Query(context.Background(), &query, variables)
	if err != nil {
		fmt.Println("Error fetching job:", err)
		return
	}

	fmt.Printf("Name: %s, Quantity: %d\n", query.Job.Name, query.Job.Quantity)
}

5. Error Handling

Implement error handling to manage potential issues during the request:

go
err := client.Query(context.Background(), &query, variables)
if err != nil {
	fmt.Println("Error fetching job:", err)
	return
}

6. Explore API Documentation

For detailed information on available queries, mutations, and schema definitions, refer to the CoCore API documentation at https://docs.wearecococo.com.

By following these steps, Go developers can effectively integrate with the CoCore GraphQL API using the go-graphql-client library.

Connect. Combine. Collaborate.
The pioneering open integration platform, dedicated to transforming connectivity in the printing industry.