Skip to content

Defining Contracts

Contracts are YAML files that define the shape and rules for your API endpoints. ContractShield validates incoming requests against these contracts before they reach your application code.

Contract Structure

contracts/users-update.yaml
endpoint: /api/users/:id
method: PUT
schema:
# JSON Schema for request validation
invariants:
# CEL expressions for business logic

Endpoint Matching

ContractShield supports Express-style path parameters:

PatternMatches
/api/usersExact match
/api/users/:id/api/users/123, /api/users/abc
/api/orgs/:org/repos/:repo/api/orgs/acme/repos/api

Schema Validation

The schema field uses standard JSON Schema draft-07:

endpoint: /api/users
method: POST
schema:
type: object
properties:
email:
type: string
format: email
age:
type: integer
minimum: 0
maximum: 150
role:
type: string
enum: [user, admin, moderator]
required:
- email
additionalProperties: false

Supported Formats

  • email — Email addresses
  • uri — URLs
  • uuid — UUIDs
  • date — ISO 8601 dates
  • date-time — ISO 8601 timestamps
  • ipv4 / ipv6 — IP addresses

Multiple Methods

Create separate contracts for each method:

contracts/
├── users-get.yaml # GET /api/users/:id
├── users-post.yaml # POST /api/users
├── users-put.yaml # PUT /api/users/:id
└── users-delete.yaml # DELETE /api/users/:id

Contract Loading

// From directory (recommended)
contractShield({
contractsDir: './contracts', // Loads *.yaml and *.json
});
// From array
contractShield({
contracts: [
{ endpoint: '/api/users', method: 'POST', schema: { } },
],
});

IDE Support

Get autocomplete and validation in your editor:

# yaml-language-server: $schema=https://contractshield.dev/schemas/policy.v0.1.json
endpoint: /api/users
method: POST
# Your editor now provides autocomplete!

Validation Errors

When validation fails, ContractShield returns:

{
"error": "CONTRACT_VIOLATION",
"code": "SCHEMA_INVALID",
"details": [
{
"path": "/email",
"message": "must match format \"email\""
}
]
}

Next Steps