We are going to design a contract-first API development lifecycle that starts with Protobuf/IDL specifications, then creates mocks, and finally gets consumer sign-off before implementation.
Steps:
-
Define the API contract in Protobuf/IDL (using gRPC or just Protobuf for REST, but note: Protobuf is language-agnostic and can be used for both gRPC and REST via gRPC Gateway or similar).
- We'll use Protocol Buffers (protobuf) as the IDL.
- Define the service, methods, and message types.
-
Generate server stubs and client libraries from the protobuf definitions.
- We can generate code for multiple languages (e.g., Go, Java, Python, etc.) for both server and client.
-
Create mocks of the API for consumer testing.
- We can use tools like
grpcurl for gRPC or protoc-gen-mock for generating mocks in Go, or use a mock server that adheres to the contract.
-
Consumer testing and sign-off:
- Provide the mock server and client libraries to the consumer teams.
- Consumers can test against the mock server (which implements the contract but has no real logic) to verify that the contract meets their needs.
- Once the consumers are satisfied, we get sign-off (this could be a formal agreement, a pull request approval, or a meeting).
-
Implement the server:
- After sign-off, the provider team implements the actual business logic in the server stub.
-
Deploy and version:
- Deploy the server and maintain versioning (using semantic versioning and possibly multiple versions of the API if needed).
However, note that the problem asks for a lifecycle that starts with the spec and mocks, and then consumer signoff. So the critical part is steps 1-4.
Let's break down step 1 with an example.
Example: A simple key-value store API.
We define a service KeyValueStore with two RPCs: Put and Get.
We'll write a kv_store.proto file:
syntax = "proto3";
package example.kvstore.v1;
option go_package = "github.com/example/kvstore/v1;kvstorev1";
service KeyValueStore {
rpc Put(PutRequest) returns (PutResponse);
rpc Get(GetRequest) returns (GetResponse);
}
message PutRequest {
string key = 1;
string value = 2;
}
message PutResponse {
bool success = 1;
}
message GetRequest {
string key = 1;
}
message GetResponse {
string value = 1;
}
Now, we generate the server and client code for the desired languages. For example, for Go:
protoc --go_out=. --go-grpc_out=. kv_store.proto
This generates:
kv_store.pb.go (the message types)
kv_store_grpc.pb.go (the client and server interfaces)
Step 3: Create a mock server.
We can write a simple mock server in Go that implements the KeyValueStoreServer interface but uses an in-memory map and has no persistence. Alternatively, we can use a tool like grpc-mock (https://github.com/uber-go/mock) but note that grpc-mock is for generating mocks in tests, not a running server.
Alternatively, we can write a simple mock server that just returns fixed responses or echoes the input. But for a key-value store, we might want to have a simple in-memory implementation.
However, the goal of the mock is to have a running server that adheres to the contract so that consumers can test their clients. We can write a minimal implementation that does the basics.
Let's write a simple mock server in Go (assuming we generated the code for Go):
We'll create a mock_server.go:
package main
import (
"context"
"log"
"net"
"github.com/example/kvstore/v1"
"google.golang.org/grpc"
)
type mockServer struct {
store map[string]string
kvstore.UnimplementedKeyValueStoreServer
}
func (m *mockServer) Put(ctx context.Context, req *kvstore.PutRequest) (*kvstore.PutResponse, error) {
m.store[req.Key] = req.Value
return &kvstore.PutResponse{Success: true}, nil
}
func (m *mockServer) Get(ctx context.Context, req *kvstore.GetRequest) (*kvstore.GetResponse, error) {
val, ok := m.store[req.Key]
if !ok {
// Return empty string? Or an error? The proto doesn't define an error for Get.
// We'll return empty string if not found.
return &kvstore.GetResponse{Value: ""}, nil
}
return &kvstore.GetResponse{Value: val}, nil
}
func main() {
lis, err := net.Listen("tcp", ":50051")
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
s := grpc.NewServer()
kvstore.RegisterKeyValueStoreServer(s, &mockServer{store: make(map[string]string)})
log.Println("Mock server listening on :50051")
if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}
Then we can build and run this mock server.
Alternatively, we can use a tool like grpcurl to test the mock server, but the consumer will use their own client.
Step 4: Consumer sign-off.
We can provide the consumer with:
- The protobuf contract (the
.proto file)
- The mock server (or instructions to run it) so they can test their client against a known implementation.
- The client library for their language (if we generated it) or instructions to generate it.
The consumer then tests their client with the mock server and reports back if the contract meets their needs.
We might have an iterative process: if the consumer finds issues, we update the .proto file and repeat.
Once the consumer signs off (e.g., by approving a pull request that updated the .proto file and the mock server, or by a formal sign-off document), we proceed to implementation.
Step 5: The provider team implements the real server, using the same .proto file and the generated server stub. They fill in the Put and Get methods with the real logic (e.g., connecting to a database).
Step 6: Deploy and version.
We can use a versioning scheme in the package name (e.g., example.kvstore.v1). If we need to make breaking changes, we create a new version (e.g., v2) and update the package and service names accordingly.
This is a high-level lifecycle.
However, note that the problem says "starting with protobuf/IDL specs, mocks, and consumer signoff". So the key is that the contract is defined first, then mocks are created, and then the consumer signs off before the provider writes any business logic.
This ensures that the contract is agreed upon by both parties and that the consumer's client can be developed in parallel (or at least tested) without waiting for the server implementation.
Additional considerations:
-
We might want to use a contract testing tool (like Pact) but note that Pact is more for consumer-driven contracts. Here we are doing provider-driven? Actually, the process described is more of a design-first where the provider defines the contract and then the consumer signs off. This is common in gRPC and Protobuf-based APIs.
-
Alternatively, we can use a tool like protoc-gen-validate to add validation rules to the protobuf definitions, so the contract includes validation.
-
We might also generate documentation (like using protoc-gen-doc or grpc-gateway for REST) and share that with the consumer.
-
We can also set up a CI pipeline that:
- Lints the protobuf files.
- Generates code for all target languages and checks that it compiles (or even runs tests against the mock server?).
- Runs the mock server and maybe some basic smoke tests.
But the core of the process is:
Design (protobuf) -> Mock server -> Consumer sign-off -> Implementation.
Let's write a step-by-step guide for a team:
Step-by-step guide for the team:
-
Design the API:
- The API designer (or a team including both provider and consumer) writes the protobuf file(s).
- The file should be stored in a shared repository (or the provider's repo if that's the agreement).
-
Generate code and create mock server:
- The provider team generates the server and client stubs for the languages they support.
- They create a mock server (like the one above) that implements the contract but with in-memory or dummy data.
-
Share with consumers:
- The provider shares the protobuf file and the mock server (or a Docker image, or instructions to run it).
- They also share the generated client libraries (or the way to generate them) for the consumer's language.
-
Consumer testing:
- The consumer team writes their client code (or uses the generated client) and tests it against the mock server.
- They may also write integration tests that run against the mock server.
-
Sign-off:
- The consumer team reviews the contract (the protobuf file) and the behavior of the mock server.
- If they agree, they sign off (e.g., by approving a pull request that adds the protobuf file to their repository, or by a formal document).
- If they have changes, they request changes and we go back to step 1.
-
Implementation:
- The provider team implements the real server, using the same protobuf file and the generated server stub.
- They replace the mock implementation with real business logic and data access.
-
Deployment:
- The provider deploys the server and makes it available.
- The consumer updates their client to point to the real server.
-
Versioning:
- If the contract needs to change in a breaking way, we follow semantic versioning and create a new version of the API (e.g., v2) and repeat the process.
This process avoids the situation where the consumer writes a client and then finds out the server doesn't implement what they expected.
However, note that the consumer might also have a say in the design. So it's important to involve the consumer in the design phase (step 1) as much as possible.
We can also consider using a tool like grpc-gateway to generate RESTful JSON APIs from the same protobuf definitions, if we want to support both gRPC and REST.
But the core is the same: define the contract first, then mocks, then sign-off, then implementation.
Let me know if you have any questions or need more details on a specific step.
I'll design a comprehensive contract-first API development lifecycle that starts with IDL specifications and ensures consumer validation before implementation. This approach shifts API development left, reducing integration failures and improving developer experience.
🏗️ Contract-First API Lifecycle Architecture
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
│ 1. IDL Spec │───▶│ 2. Mock Gen │───▶│ 3. Consumer │
│ Definition │ │ & Deployment │ │ Testing & │
│ │ │ │ │ Sign-off │
└─────────────────┘ └──────────────────┘ └─────────────────┘
│ │ │
▼ ▼ ▼
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
│ 4. Provider │ │ 5. Integration │ │ 6. Contract │
│ Implementation │◀───│ Test Suite │◀───│ Validation │
│ │ │ │ │ & CI/CD │
└─────────────────┘ └──────────────────┘ └─────────────────┘
📋 Phase 1: IDL Specification & Design
A. Protobuf/IDL Definition Process
// api/v1/service/order_service.proto
syntax = "proto3";
package api.v1.order;
option go_package = "gen/go/api/v1/order;orderv1";
option java_multiple_files = true;
option java_package = "com.example.api.v1.order";
import "google/protobuf/timestamp.proto";
import "google/protobuf/empty.proto";
import "api/v1/common/common.proto";
service OrderService {
// Unary RPC
rpc CreateOrder(CreateOrderRequest) returns (Order) {}
rpc GetOrder(GetOrderRequest) returns (Order) {}
// Server streaming
rpc StreamOrders(StreamOrdersRequest) returns (stream Order) {}
// Client streaming
rpc BatchCreateOrders(stream CreateOrderRequest)
returns (BatchCreateOrdersResponse) {}
// Bidirectional streaming
rpc OrderChat(stream OrderChatMessage)
returns (stream OrderChatMessage) {}
}
// Request/Response patterns
message CreateOrderRequest {
string customer_id = 1 [(validate.rules).string = {min_len: 1, max_len: 100}];
repeated OrderItem items = 2 [(validate.rules).repeated = {min_items: 1}];
api.v1.common.Money total_amount = 3;
google.protobuf.Timestamp requested_by = 4;
message OrderItem {
string product_id = 1;
int32 quantity = 2 [(validate.rules).int32 = {gt: 0}];
api.v1.common.Money unit_price = 3;
}
}
message Order {
string id = 1;
string customer_id = 2;
repeated OrderItem items = 3;
api.v1.common.Money total_amount = 4;
OrderStatus status = 5;
google.protobuf.Timestamp created_at = 6;
google.protobuf.Timestamp updated_at = 7;
enum OrderStatus {
ORDER_STATUS_UNSPECIFIED = 0;
PENDING = 1;
CONFIRMED = 2;
SHIPPED = 3;
DELIVERED = 4;
CANCELLED = 5;
}
}
B. Design Artifacts & Validation
.proto files with:
- Comprehensive comments explaining business logic
- Field validation rules (using
protoc-gen-validate)
- Semantic versioning in package names (
package api.v1.order;)
- Import common types from shared
common.proto
- API Specification Document:
- Service SLAs (latency, throughput)
- Error code taxonomy (using gRPC status codes + custom codes)
- Authentication/authorization requirements
- Rate limiting policies
- Pagination standards
C. Tooling Setup
# .prototool.yaml (or similar config)
version: v1
plugins:
- name: go
output: gen/go
opt: paths=source_relative,plugins=grpc
- name: grpc-gateway
output: gen/go
opt: paths=source_relative,logtostderr=true
- name: java
output: gen/java
- name: validate
output: gen
🤖 Phase 2: Mock Generation & Deployment
A. Automated Mock Generation
# Generate server mocks using mockery or grpcmock
# For Go:
mockery --dir=gen/go/api/v1/order --name=OrderServiceServer --output=mocks/
# Generate mock server with predefined responses
mock-server-generator \
--proto=api/v1/order/order_service.proto \
--output=mock-server \
--scenario=happy-path,error-cases,edge-cases \
--response-config=mock-responses.yaml
Example mock responses config (mock-responses.yaml):
scenarios:
happy_path:
CreateOrder:
response:
id: "ord_12345"
status: "CONFIRMED"
total_amount: { currency: "USD", value: "99.99" }
delay: 100ms
GetOrder:
response:
id: "{{request.id}}"
status: "PENDING"
error_cases:
CreateOrder:
- request: { customer_id: "" }
response:
code: INVALID_ARGUMENT
message: "customer_id is required"
- request: { items: [] }
response:
code: INVALID_ARGUMENT
message: "at least one item required"
B. Deployable Mock Service
# Dockerfile for mock server
FROM golang:1.21-alpine AS builder
WORKDIR /app
COPY . .
RUN go build -o mock-server ./cmd/mock-server
FROM alpine:latest
COPY --from=builder /app/mock-server .
EXPOSE 50051 8080
CMD ["./mock-server", "--config", "/config/mock-responses.yaml"]
Run mock server with scenario selection:
docker run -p 50051:50051 \
-v $(pwd)/mock-responses.yaml:/config/mock-responses.yaml \
order-service-mock:latest \
--scenario=happy-path,validation-errors
👥 Phase 3: Consumer Testing & Sign-off
A. Consumer Testing Package
contract-test-kit/
├── README.md # Quick start guide
├── mock-server/ # Docker compose for mock server
│ ├── docker-compose.yaml
│ └── scenarios/ # Predefined test scenarios
├── client-libraries/ # Generated clients for all consumers
│ ├── java/
│ ├── python/
│ ├── typescript/
│ └── go/
├── contract-tests/ # Integration tests against mock
│ ├── java/src/test/java/com/example/contract/
│ ├── python/tests/contract/
│ └── typescript/__tests__/
├── test-data/ # Sample payloads
│ ├── valid-requests.json
│ ├── invalid-requests.json
│ └── edge-cases.json
└── validation-tools/ # Contract validation CLI
└── contract-validator
B. Consumer Sign-off Workflow
## Consumer Sign-off Checklist
### ✅ Contract Validation
- [ ] All required fields present in responses
- [ ] Error codes match documentation
- [ ] Field naming conventions consistent
- [ ] Data types match consumer expectations
- [ ] Enums cover all required states
### ✅ Functional Testing
- [ ] Happy path tests pass (n=100)
- [ ] Error handling tests pass
- [ ] Boundary value tests pass
- [ ] Concurrent request tests pass
- [ ] Streaming behavior validated (if applicable)
### ✅ Non-Functional Requirements
- [ ] Mock server latency meets SLA requirements
- [ ] Payload size within limits
- [ ] Authentication flows work
- [ ] Rate limiting behavior acceptable
### ✅ Documentation
- [ ] Example requests/resolutions reviewed
- [ ] Error message clarity verified
- [ ] Field descriptions sufficient
**Sign-off Authority**: [Consumer Team Lead Name]
**Date**: _______________
**Contract Version**: api/v1/order/v1.2.0
C. Automated Contract Testing
# contract-tests/python/tests/test_order_contract.py
import pytest
from order_service_v1 import OrderServiceStub
from contract_test_kit import MockServerManager
class TestOrderContract:
@pytest.fixture(scope="module")
def mock_server(self):
with MockServerManager(scenario="happy_path") as server:
yield server
def test_create_order_success(self, mock_server):
client = OrderServiceStub(mock_server.channel)
request = CreateOrderRequest(
customer_id="cust_123",
items=[OrderItem(product_id="prod_456", quantity=2)],
total_amount=Money(currency="USD", value="29.98")
)
response = client.CreateOrder(request)
assert response.id.startswith("ord_")
assert response.status == OrderStatus.CONFIRMED
def test_create_order_validation_error(self, mock_server):
client = OrderServiceStub(mock_server.channel)
request = CreateOrderRequest(customer_id="") # Invalid
with pytest.raises(grpc.RpcError) as exc:
client.CreateOrder(request)
assert exc.value.code() == grpc.StatusCode.INVALID_ARGUMENT
assert "customer_id" in exc.value.details()
⚙️ Phase 4: Consumer-Driven Contract Validation
A. Contract Validation CLI Tool
// validation-tools/contract-validator/main.go
package main
import (
"fmt"
"os"
"github.com/ghodss/yaml"
"google.golang.org/protobuf/reflect/protoreflect"
)
type ContractValidator struct {
protoDesc protoreflect.FileDescriptor
consumerTests []ConsumerTestSuite
}
func (cv *ContractValidator) Validate() error {
// 1. Check all consumer tests against spec
// 2. Generate compatibility report
// 3. Check for breaking changes vs previous version
// 4. Validate error code coverage
// 5. Generate test coverage matrix
report := cv.generateReport()
fmt.Printf("Contract Coverage: %d%%\n", report.Coverage)
if report.BreakingChanges {
return fmt.Errorf("breaking changes detected")
}
return nil
}
B. CI/CD Pipeline Integration
# .github/workflows/contract-validation.yaml
name: Contract Validation
on:
pull_request:
paths:
- 'api/**/*.proto'
- 'contract-test-kit/**'
jobs:
validate-contract:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up Go
uses: actions/setup-go@v4
with:
go-version: '1.21'
- name: Generate code
run: |
make generate
- name: Build mock server
run: |
docker build -t order-mock -f cmd/mock-server/Dockerfile .
- name: Start mock server
run: |
docker run -d -p 50051:50051 --name mock order-mock
- name: Run contract tests
run: |
# Run tests from all consumer languages
make test-contracts
- name: Validate contract changes
run: |
./validation-tools/contract-validator \
--proto=api/v1/order/order_service.proto \
--previous-version=$(git rev-parse origin/main:api/v1/order/order_service.proto) \
--output=validation-report.md
- name: Upload validation report
uses: actions/upload-artifact@v3
with:
name: contract-validation-report
path: validation-report.md
🔄 Phase 5: Version Management & Governance
A. Semantic Versioning for APIs
// Version encoded in package and service names
package api.v1.order.v1_2_0; // Major.Minor.Patch
service OrderServiceV1_2_0 { // Version in service name
rpc CreateOrder(...) {...}
}
// Backward compatible changes (same major version):
// - Add new optional fields
// - Add new RPC methods
// - Add new enum values
// Breaking changes require major version bump:
// - Remove required fields
// - Change field types
// - Remove RPC methods
B. API Change Approval Process
## API Change Request Form
### Basic Info
- **API**: Order Service
- **Current Version**: v1.2.0
- **Proposed Version**: v1.3.0
- **Change Type**: ☐ Breaking ☐ Non-breaking
### Change Description
[Describe the change]
### Impact Analysis
| Consumer | Impact | Mitigation |
|----------|--------|------------|
| Mobile App | New field required | Update SDK |
| Web Client | New field optional | No action needed |
### Testing
- [ ] All existing contract tests pass
- [ ] New contract tests added
- [ ] Mock server updated
- [ ] Documentation updated
### Sign-offs
| Team | Approved By | Date |
|------|-------------|------|
| Mobile | ___________ | ____ |
| Web | ___________ | ____ |
| Provider | ___________ | ____ |
📊 Phase 6: Monitoring & Feedback Loop
A. Post-Deployment Contract Monitoring
# contract-monitoring/kubernetes/monitoring.yaml
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
name: order-api-contract-monitor
spec:
selector:
matchLabels:
app: order-api
endpoints:
- port: metrics
interval: 30s
path: /metrics/contract
metricRelabelings:
- sourceLabels: [contract_violation]
action: keep
regex: true
Contract violation metrics to monitor:
# Contract violations by type
contract_violations_total{type="missing_required_field",api="order/v1"}
contract_violations_total{type="unexpected_field",api="order/v1"}
contract_violations_total{type="wrong_type",api="order/v1"}
# Consumer compatibility score
consumer_compatibility_score{consumer="mobile-app",version="v1.2.0"}=0.98
B. Feedback Loop to Design
# Automated feedback from production
class ContractFeedbackLoop:
def analyze_production_violations(self):
violations = self.query_contract_violations()
for violation in violations:
if violation.frequency > threshold:
self.create_design_ticket(
title=f"Contract issue: {violation.type}",
description=self.format_violation_report(violation),
priority=self.calculate_priority(violation),
suggested_fix=self.suggest_fix(violation)
)
🛠️ Recommended Toolchain
| Phase | Tools (Language Agnostic) | Go | Java | Python | TypeScript |
|---|
| IDL | Protocol Buffers, AsyncAPI | ✅ | ✅ | ✅ | ✅ |
| Validation | protoc-gen-validate, Spectral | ✅ | ✅ | ✅ | ✅ |
| Mock Gen | MockServer, WireMock, grpc-mock | ✅ | ✅ | ✅ | ✅ |
| Client Gen | protoc-gen-grpc-gateway, OpenAPI Generator | ✅ | ✅ | ✅ | ✅ |
| Contract Test | Pact, Schemathesis, Postman | ✅ | ✅ | ✅ | ✅ |
| CI/CD | GitHub Actions, GitLab CI, Jenkins | ✅ | ✅ | ✅ | ✅ |
| Documentation | Buf, Spectral, Redoc | ✅ | ✅ | ✅ | ✅ |
| Monitoring | Prometheus, OpenTelemetry | ✅ | ✅ | ✅ | ✅ |
📝 Implementation Checklist
Before Implementation Starts:
During Implementation:
After Implementation:
🎯 Key Success Metrics
- Contract Coverage: % of consumer scenarios tested against mock
- Sign-off Time: Days from spec freeze to consumer sign-off
- Breaking Changes: # of breaking changes in production
- Contract Violations: # of violations detected in production
- Consumer Satisfaction: Survey score from consumer teams
This lifecycle ensures:
- ✅ Consumers validate early - before provider implementation
- ✅ Single source of truth -
.proto files define everything
- ✅ Automated verification - CI/CD enforces contract compliance
- ✅ Clear versioning - Semantic versioning in package names
- ✅ Production safety - Contract violation monitoring
- ✅ Reduced integration hell - 80%+ of issues caught pre-deployment
Would you like me to elaborate on any specific component, such as the mock server implementation details, contract testing strategies for specific languages, or governance model for multiple consumer teams?