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
endpoint: /api/users/:idmethod: PUTschema: # JSON Schema for request validationinvariants: # CEL expressions for business logicEndpoint Matching
ContractShield supports Express-style path parameters:
| Pattern | Matches |
|---|---|
/api/users | Exact 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/usersmethod: POSTschema: 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: falseSupported Formats
email— Email addressesuri— URLsuuid— UUIDsdate— ISO 8601 datesdate-time— ISO 8601 timestampsipv4/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/:idContract Loading
// From directory (recommended)contractShield({ contractsDir: './contracts', // Loads *.yaml and *.json});
// From arraycontractShield({ 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.jsonendpoint: /api/usersmethod: 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
- CEL Invariants — Add business logic rules
- Vulnerability Checks — Built-in security