liveBook · Manning

Contract

As explained in gRPC Microservices in Go

An API is an interface that exposes an application's core functionality to other software modules or external consumers.

A contract states how another component can use an application's functionality. At a service boundary, it names operations and their request and response messages. Inside a hexagonal application, a Go interface can serve the same purpose: an API port exposes core actions, while a database port specifies the operations the application needs from storage. section 2.5.1 section 4.2.4

To put a gRPC service contract to work:

  • Define request and response messages and service functions in a .proto file. For payment creation, the operation accepts CreatePaymentRequest and returns CreatePaymentResponse. section 2.5.1
  • Generate client and server stubs, implement the server's business logic, and call it through the client stub. Generated stubs let services written in different languages communicate. section 2.5.1 section 1.3
  • Choose the public-facing form deliberately. Internal gRPC may be suitable, but customers may need an SDK, shared service definitions, call instructions, or a REST-compatible interface. Maintaining proto definitions can be disproportionate for a one- or two-service application. section 1.3
package ports
 
import "github.com/huseyinbabal/microservices/order/internal/application/core/domain"
 
type APIPort interface {
    PlaceOrder(order domain.Order) (domain.Order, error)
}

The APIPort interface makes PlaceOrder the Order application's exposed action and fixes its argument, result, and error signature. section 4.2.4

A contract also gives tests a boundary to replace. Mock implementations matching the database and payment interfaces let an Order application test successful placement, persistence errors, and payment errors without relying on those dependencies. A changed gRPC service definition can likewise surface a client-side test failure. section 7.2.4 section 1.3

How gRPC Microservices in Go covers it

How deep it goes
Works through .proto messages, stub generation, and Go port signatures, but does not detail protocol internals.
Examples
Uses a Payment creation request and response, an Order API port, and mocked database and payment calls.
What it assumes
Introduces message, service, and port definitions while assuming familiarity with application services and Go interface implementation.
What you can do after
Build it from scratch with .proto definitions and generated stubs, or implement Go port interfaces for application boundaries.
How it connects
Connects contracts to gRPC, Protocol Buffers, hexagonal architecture, client stubs, and mock-based testing.

Also explained in

Compare how 44 books explain contract →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of gRPC Microservices in Go. The section links point to the parts of the book it draws on.