Docs / Write contracts

Go SDK

How to write a service's contract from its Go code with the Go SDK: installation, an example with declarations and struct tags, the GraphQL consumer and graph, the generate command and the flow to publish. The full reference is the SDK's README.

On this page

The Go SDK writes the contract file of a service from its Go code. You declare in Go code the REST resources the service provides or consumes, or the GraphQL fields it calls, mark the fields of each schema with the bidirekt struct tag, run generate, and get contracts/generated.yaml, which validate and publish take like any other contract file. It reads the source code and never runs your app.

This page shows how it reads. Every declaration, tag option, type and error is in the SDK's README β†—.

Install#

The SDK is two Go modules: github.com/bidirekt/go-sdk, the bidirekt package your code imports, which builds with Go 1.18 or later, and github.com/bidirekt/go-sdk/cmd/go-sdk, the generate command, which needs Go 1.26 or later. In the module of your service, get the package, add the command as a tool, and tidy the module once your first declaration is written:

terminal
$ go get github.com/bidirekt/go-sdk
$ go get -tool github.com/bidirekt/go-sdk/cmd/go-sdk
$ go mod tidy

Installing the command changes your go.mod: the go line goes up to 1.26.0 when it is older, and the golang.org/x modules your app already uses move up to the versions the command needs. In a go.work workspace, the go line of go.work goes up to 1.26.0 too. An app that vendors its dependencies stops with inconsistent vendoring on go build and generate until you run go mod vendor. Installation β†— in the README lists every change, and how to keep the runtime defaults of the Go version you had.

Example#

petstore_go is a net/http service in the module example.com/petstore. It provides GET /pets, GET /pets/* and POST /pets, and consumes GET /ratings/* from petstore_reviews. A struct with a field marked bidirekt:"field" is a schema, and only its marked fields are in the contract; a field without the tag, like CreatedBy, stays out. Pet uses each kind of field:

go
// pets/pet.go
package pets

import "github.com/bidirekt/go-sdk"

type PetStatus string

const (
	PetStatusAvailable PetStatus = "available"
	PetStatusAdopted   PetStatus = "adopted"
)

var _ = bidirekt.Enum(PetStatusAvailable, PetStatusAdopted)

type Owner struct {
	Name string `json:"name" bidirekt:"field"`
}

type Shelter struct {
	City string `json:"city" bidirekt:"field"`
}

type Adopter interface{ adopter() }

func (Owner) adopter()   {}
func (Shelter) adopter() {}

type Pet struct {
	ID int64 `json:"id" bidirekt:"field"`

	Name string `json:"name" bidirekt:"field"`

	Status PetStatus `json:"status" bidirekt:"field"`

	Owner Owner `json:"owner" bidirekt:"field"`

	Tags []string `json:"tags" bidirekt:"field"`

	Notes map[string]string `json:"notes" bidirekt:"field"`

	Weight float64 `json:"weight" bidirekt:"field description='In kilograms'"`

	BirthDate *string `json:"birthDate" bidirekt:"field"`

	AdoptedFrom Adopter `json:"adoptedFrom" bidirekt:"field union={person: Owner, shelter: Shelter}"`

	Nickname string `json:"nickname,omitempty" bidirekt:"field"`

	CreatedBy string `json:"-"`
}

type NewPet struct {
	Name string `json:"name" bidirekt:"field"`
}

bidirekt.RestProvides declares a resource the service provides, next to the handler that serves it. The mux routes /pets/{id} to getPet, and the path is declared /pets/*: a * for each dynamic segment, never the router's placeholder. bidirekt.Request declares the body the handler reads, and bidirekt.Response each status. A body is a value of its type, []pets.Pet{} for a list of it, or nil for no body:

go
// main.go
package main

import (
	"encoding/json"
	"net/http"

	"example.com/petstore/pets"
	"github.com/bidirekt/go-sdk"
)

var store = map[string]pets.Pet{}

var _ = bidirekt.RestProvides(
	http.MethodGet,
	"/pets",
	bidirekt.Response(http.StatusOK, []pets.Pet{}),
)

func listPets(w http.ResponseWriter, r *http.Request) {
	list := []pets.Pet{}
	for _, pet := range store {
		list = append(list, pet)
	}
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(list)
}

var _ = bidirekt.RestProvides(
	http.MethodGet,
	"/pets/*",
	bidirekt.Response(http.StatusOK, pets.Pet{}),
	bidirekt.Response(http.StatusNotFound, nil),
)

func getPet(w http.ResponseWriter, r *http.Request) {
	pet, found := store[r.PathValue("id")]
	if !found {
		w.WriteHeader(http.StatusNotFound)
		return
	}
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(pet)
}

var _ = bidirekt.RestProvides(
	http.MethodPost,
	"/pets",
	bidirekt.Request(pets.NewPet{}),
	bidirekt.Response(http.StatusCreated, pets.Pet{}),
	bidirekt.Response(http.StatusBadRequest, nil),
)

func createPet(w http.ResponseWriter, r *http.Request) {
	var request pets.NewPet
	if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
		w.WriteHeader(http.StatusBadRequest)
		return
	}
	pet := pets.Pet{Name: request.Name, Status: pets.PetStatusAvailable}
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusCreated)
	json.NewEncoder(w).Encode(pet)
}

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("GET /pets", listPets)
	mux.HandleFunc("GET /pets/{id}", getPet)
	mux.HandleFunc("POST /pets", createPet)
	http.ListenAndServe(":8080", mux)
}

bidirekt.RestConsumes declares a resource a client consumes, and names the provider:

go
// ratings.go
package main

import (
	"encoding/json"
	"net/http"

	"github.com/bidirekt/go-sdk"
)

type Rating struct {
	Average float64 `json:"average" bidirekt:"field"`

	Count int `json:"count" bidirekt:"field"`
}

var _ = bidirekt.RestConsumes(
	"petstore_reviews",
	http.MethodGet,
	"/ratings/*",
	bidirekt.Response(http.StatusOK, Rating{}),
	bidirekt.Response(http.StatusNotFound, nil),
)

func fetchRating(petID string) (*Rating, error) {
	response, err := http.Get("http://petstore-reviews/ratings/" + petID)
	if err != nil {
		return nil, err
	}
	defer response.Body.Close()
	if response.StatusCode == http.StatusNotFound {
		return nil, nil
	}
	var rating Rating
	err = json.NewDecoder(response.Body).Decode(&rating)
	return &rating, err
}

Run generate in the project folder, the one with go.mod:

terminal
$ go tool go-sdk generate

It writes contracts/generated.yaml. The list []pets.Pet{} becomes the PetList schema:

yaml
# Generated by github.com/bidirekt/go-sdk. Do not edit.
provides:
  rest:
    /pets:
      get:
        responses:
          200: PetList
      post:
        request: NewPet
        responses:
          201: Pet
          400: ~
    /pets/*:
      get:
        responses:
          200: Pet
          404: ~
consumes:
  petstore_reviews:
    rest:
      /ratings/*:
        get:
          responses:
            200: Rating
            404: ~
schemas:
  NewPet:
    type: object
    properties:
      name:
        type: string
  Owner:
    type: object
    properties:
      name:
        type: string
  Pet:
    type: object
    properties:
      id:
        type: integer
      name:
        type: string
      status:
        ref: PetStatus
      owner:
        ref: Owner
      tags:
        type: array
        items:
          type: string
      notes:
        type: map
        values:
          type: string
      weight:
        type: number
        description: In kilograms
      birthDate:
        type: string
        nullable: true
      adoptedFrom:
        type: union
        members:
          person:
            ref: Owner
          shelter:
            ref: Shelter
      nickname:
        type: string
        optional: true
  PetList:
    type: array
    items:
      ref: Pet
  PetStatus:
    type: enum
    members: ["available", "adopted"]
  Rating:
    type: object
    properties:
      average:
        type: number
      count:
        type: integer
  Shelter:
    type: object
    properties:
      city:
        type: string

A named string type with bidirekt.Enum is a ref to an enum schema, a schema struct is a ref, a pointer is nullable, a slice is an array and a map a map. Without bidirekt.Request a resource has no request key, and bidirekt.Request(nil) writes request: ~. weight is a number because encoding/json writes the float64 50.0 as 50 (What encoding/json writes β†—). A field of an interface type is a union when its tag names the schema of each member in union. A description with a space goes between single quotes, since the whole tag is already a Go string in double quotes.

Unions, embedded and anonymous structs β†— in the README shows embedded and anonymous structs, and how bidirekt.Named and bidirekt.Schema name a schema.

bidirekt.Provides and bidirekt.Consumes, the names before RestProvides and RestConsumes, are deprecated: they still compile and generate the same contract, and generate warns where it finds them.

GraphQL#

For GraphQL, the SDK writes what a service consumes, and the graph of a subgraph. A provider publishes the GraphQL schema its application already has, which the SDK does not write (GraphQL: Resources).

bidirekt.GraphqlConsumes declares a field the service calls: the provider, bidirekt.Query or bidirekt.Mutation with the field's name, bidirekt.Arguments with the struct of the arguments it sends, and bidirekt.Returns with a value of the type it reads. bidirekt.Scalar[T]("DateTime") declares that the Go type T is the GraphQL custom scalar DateTime, and arguments= in a field's tag names the arguments the call passes to that field. Here petstore_web calls the GraphQL API of petstore_api:

go
// petstore.go
package main

import (
	"time"

	"github.com/bidirekt/go-sdk"
)

var _ = bidirekt.Scalar[time.Time]("DateTime")

type PetArgs struct {
	ID string `json:"id" bidirekt:"field"`
}

type ReviewsArgs struct {
	First int `json:"first" bidirekt:"field"`
}

type Review struct {
	Stars int `json:"stars" bidirekt:"field"`
}

type Pet struct {
	Name string `json:"name" bidirekt:"field"`

	BornAt *time.Time `json:"bornAt" bidirekt:"field"`

	Reviews []Review `json:"reviews" bidirekt:"field arguments=ReviewsArgs"`
}

var _ = bidirekt.GraphqlConsumes("petstore_api", bidirekt.Query("pets"), bidirekt.Returns([]Pet{}))

var _ = bidirekt.GraphqlConsumes("petstore_api", bidirekt.Query("petCount"), bidirekt.Returns(0))

var _ = bidirekt.GraphqlConsumes("petstore_api", bidirekt.Query("pet"),
	bidirekt.Arguments(PetArgs{}),
	bidirekt.Returns((*Pet)(nil), bidirekt.Named("MaybePet")),
)

generate writes the calls under consumes.petstore_api.graphql. A returns that is not a schema returned as it is becomes a schema of its own: []Pet{} is PetList, 0 is Integer, and (*Pet)(nil) with bidirekt.Named("MaybePet") is MaybePet; without bidirekt.Named it would be PetOrNull:

yaml
# Generated by github.com/bidirekt/go-sdk. Do not edit.
consumes:
  petstore_api:
    graphql:
      query:
        pet:
          arguments: PetArgs
          returns: MaybePet
        petCount:
          returns: Integer
        pets:
          returns: PetList
schemas:
  Integer:
    type: integer
  MaybePet:
    ref: Pet
    nullable: true
  Pet:
    type: object
    properties:
      name:
        type: string
      bornAt:
        type: scalar
        name: DateTime
        nullable: true
      reviews:
        type: array
        items:
          ref: Review
        arguments: ReviewsArgs
  PetArgs:
    type: object
    properties:
      id:
        type: string
  PetList:
    type: array
    items:
      ref: Pet
  Review:
    type: object
    properties:
      stars:
        type: integer
  ReviewsArgs:
    type: object
    properties:
      first:
        type: integer

A field of a type declared with bidirekt.Scalar is that scalar, in a slice or behind a pointer too. scalar=DateTime in a field's tag does the same for one field, in place of its Go type. bidirekt.Returns also takes a type declared with bidirekt.Scalar or bidirekt.Enum, a string, a number or a boolean, in a slice or behind a pointer.

bidirekt.Union[T](A{}, B{}) declares the interface T as a union of the structs that implement it, for a call or a field that reads a GraphQL union:

go
type SearchResult interface{ isSearchResult() }

func (Pet) isSearchResult()   {}
func (Owner) isSearchResult() {}

var _ = bidirekt.Union[SearchResult](Pet{}, Owner{})

var _ = bidirekt.GraphqlConsumes("petstore_api", bidirekt.Query("search"), bidirekt.Returns([]SearchResult{}))
yaml
  SearchResult:
    type: union
    members:
      Pet:
        ref: Pet
      Owner:
        ref: Owner
  SearchResultList:
    type: array
    items:
      ref: SearchResult

The key of each member is its schema name, which must be the name of its type in the provider's GraphQL schema: a struct named otherwise takes that name with bidirekt.Schema(PetView{}, bidirekt.Named("Pet")).

A type declared with bidirekt.Scalar, or with bidirekt.Union on a struct with fields of its own, exists only in GraphQL: used in a REST body, it stops generate at that field. A union declared on an interface can also be used in a REST body.

A call that reads the type name declares a field with json:"__typename" of a named string type declared with bidirekt.Enum, with the type names it reads. Like any enum, it becomes a ref to an enum schema:

go
type PetTypename string

var _ = bidirekt.Enum[PetTypename]("Pet")

type Pet struct {
	Typename PetTypename `json:"__typename" bidirekt:"field"`

	Name *string `json:"name" bidirekt:"field"`
}
yaml
  Pet:
    type: object
    properties:
      __typename:
        ref: PetTypename
      name:
        type: string
        nullable: true
  PetTypename:
    type: enum
    members: ["Pet"]

When petstore_api renames Pet to Animal, a call of pet that reads it breaks: the report is in Reading the type name. A call that reads any type name gives the json:"__typename" field the type string, written as type: string, which never breaks on a rename.

Two declarations may call the same field of the same provider with different bidirekt.Returns or bidirekt.Arguments. generate writes both, as lists in alphabetical order without repeats, with ~ first in arguments for a declaration that sends none; a field with one schema is still written as a plain name (Several schemas for one field). For example, two declarations of pets that return []PetCard{} and []PetName{} write:

yaml
        pets:
          returns: ["PetCardList", "PetNameList"]

A call whose query names a GraphQL type declares that name (Type names). bidirekt.Scalar[T] takes the built-in names too: with type PetID string, bidirekt.Scalar[PetID]("ID") writes a field of type PetID as {type: scalar, name: ID}. On a struct or a type declared with bidirekt.Enum, the option bidirekt.GraphqlType of bidirekt.Schema, alone or beside bidirekt.Named, writes name on its schema: bidirekt.Schema(PetFilter{}, bidirekt.GraphqlType("PetFilterInput")) writes name: PetFilterInput. A REST body or the struct of bidirekt.Arguments that reaches it stops generate, since neither is a GraphQL type.

The provider of bidirekt.GraphqlConsumes may be a federated graph, as petstore_graph, and the calls are then checked against the graph its subgraphs compose (Graphs). A subgraph declares its graph with var _ = bidirekt.Graph("petstore_graph") anywhere in the project, and generate writes it as provides.graphql.graph. Every subgraph of a graph declares the same name.

Describe what the code does#

The contract describes what the code does, not the type the code declares (Describe what the code does). With the SDK, the Go type is where each field starts, and the tag's options apply the rule: a declared type, optional or nullable wins over the Go type.

In the example, nickname needs no option: with omitempty, encoding/json leaves an empty nickname out of the body, and the SDK follows what it writes, so the field is optional. A *string whose database column allows null, but which the service always fills, declares bidirekt:"field nullable=false", and a time.Time the body carries as a string declares bidirekt:"field type=string".

From code to deploy#

contracts/generated.yaml is the service's contract file: a service adopts the SDK as a whole, with every resource and schema it provides or consumes declared in its code. A subgraph's contract is that file together with its GraphQL schema (GraphQL). Regenerate the file whenever a declaration or a marked type changes, and commit it with the code. Then the flow is the same as with a hand-written file:

terminal
$ go tool go-sdk generate
$ bidirekt validate
$ bidirekt validate --participant petstore_go --environment production
$ bidirekt publish --participant petstore_go --version 1.4.0
$ bidirekt can-i-deploy petstore_go --version 1.4.0 --environment production
$ bidirekt record-deployment petstore_go --version 1.4.0 --environment production

Without file arguments, validate and publish read the contracts/ folder of the current directory (The contracts folder). validate without --participant and --environment checks only the file; with them, it also compares the file with what is deployed in that environment. Deploy between can-i-deploy and record-deployment. In CI, go tool go-sdk generate --check fails the build when the committed file is out of date. generate --project <folder> reads another project and writes to its contracts/ folder, so a module with cmd/api and cmd/worker generates one contract per service (go tool go-sdk generate --project cmd/worker), published with bidirekt publish cmd/worker/contracts/ --participant petstore_worker --version 1.4.0; --out <file> writes to another file.

A subgraph, a service that declares its graph with bidirekt.Graph, passes its GraphQL schema next to the folder, as bidirekt validate contracts/ graph/schema.graphqls and bidirekt publish contracts/ graph/schema.graphqls --participant petstore_reviews --version 2.0.0: contracts/ alone fails with graph "petstore_graph" without a GraphQL schema.

The broker reads every file of one publish as one contract (Several files), but the SDK cannot see a hand-written file: a tag cannot name a schema declared only there, and a schema or a provided resource declared both in the code and in a hand-written file is rejected at publish as declared twice. A consumed resource declared in both is merged, like the fragments of one consumer (Several files). To adopt the SDK, declare every resource and schema the service provides or consumes, generate, check that the new file declares what the old files did, and delete the old files.

When can-i-deploy reports a break, fix the declaration or the tag in the code and generate again. Never edit contracts/generated.yaml: the next generate writes over it.

A type the contract cannot hold, such as time.Time or any without a declared type, stops generate with the file and the line, and nothing is written. The generate command β†— and the Reference β†— of the README list every declaration, tag option, type and error.