-
Notifications
You must be signed in to change notification settings - Fork 59
Contracts
API contracts define the agreement between frontend and backend. Drift detects mismatches automatically.
An API contract is the implicit agreement between code that calls an API and code that implements it:
// Frontend expects:
fetch('/api/users/123')
.then(res => res.json())
.then(data => {
console.log(data.user.name); // Expects { user: { name: string } }
});
// Backend provides:
app.get('/api/users/:id', (req, res) => {
res.json({ data: user }); // Returns { data: User } β MISMATCH!
});Drift detects these mismatches before they cause runtime errors.
Frontend Code βββ
ββββ Drift Analyzes βββ Contract βββ Verified/Mismatch
Backend Code ββββ
- Discovery β Drift finds API calls in frontend and endpoints in backend
- Matching β Drift matches calls to endpoints by path and method
- Verification β Drift compares expected vs actual response shapes
- Status β Contracts are marked as verified, mismatch, or discovered
| Status | Meaning |
|---|---|
| Verified | Frontend and backend agree |
| Mismatch | Frontend expects different shape than backend provides |
| Discovered | Found but not yet verified (needs review) |
| Ignored | Intentionally excluded from checking |
Contracts are detected during regular scans:
drift scanContract detection happens automatically as part of the scan process.
Use the drift_contracts_list MCP tool to view contracts:
{
"status": "mismatch",
"limit": 20
}Parameters:
-
statusβ Filter by status:all,verified,mismatch,discovered -
limitβ Maximum results (default: 20, max: 50) -
cursorβ Pagination cursor
Returns:
{
"summary": "45 contracts: 40 verified, 3 mismatches, 2 discovered. β οΈ 3 need attention.",
"contracts": [
{
"id": "contract-123",
"endpoint": "/api/users/:id",
"method": "GET",
"status": "mismatch",
"frontendFile": "src/api/users.ts",
"backendFile": "src/routes/users.ts",
"mismatchCount": 1
}
],
"stats": {
"verified": 40,
"mismatch": 3,
"discovered": 2
}
}// Before
res.json({ data: user });
// After
res.json({ user });// Before
const { user } = await response.json();
// After
const { data: user } = await response.json();Mark contracts as intentionally different using the MCP tool or by configuring ignore paths.
Drift detects API calls in:
| Pattern | Example |
|---|---|
fetch() |
fetch('/api/users') |
axios |
axios.get('/api/users') |
$http |
$http.get('/api/users') |
| Custom clients | apiClient.get('/users') |
Drift detects endpoints in:
| Framework | Pattern |
|---|---|
| Express | app.get('/api/users', handler) |
| NestJS | @Get('/users') |
| FastAPI | @app.get('/users') |
| Django | path('users/', views.users) |
| Spring | @GetMapping("/users") |
| Laravel | Route::get('/users', ...) |
| Gin | r.GET("/users", handler) |
| Actix | web::get().to(handler) |
Drift analyzes response shapes by:
- Type inference β From TypeScript types, JSDoc, or runtime analysis
- Pattern matching β Common response envelope patterns
- Static analysis β What the code actually returns
// Direct return
res.json(user); // Shape: User
// Envelope pattern
res.json({ data: user }); // Shape: { data: User }
// With metadata
res.json({
data: user,
meta: { timestamp: Date.now() }
}); // Shape: { data: User, meta: { timestamp: number } }
// Error response
res.status(400).json({ error: 'Invalid input' }); // Shape: { error: string }Use the quality gate to check contracts:
drift gate --gates contract-verification- name: Check API Contracts
run: |
drift scan
drift gate --gates contract-verification --format github{
"status": "mismatch",
"limit": 20
}Parameters:
-
statusβ Filter:all,verified,mismatch,discovered -
limitβ Max results (default: 20, max: 50) -
cursorβ Pagination cursor for large result sets
Returns:
{
"summary": "3 contract mismatches found",
"contracts": [
{
"id": "contract-abc123",
"endpoint": "GET /api/users/:id",
"method": "GET",
"status": "mismatch",
"frontendFile": "src/api/users.ts",
"backendFile": "src/routes/users.ts",
"mismatchCount": 1
}
],
"stats": {
"verified": 40,
"mismatch": 3,
"discovered": 2
}
}Ask your AI agent:
"Check if there are any API contract mismatches"
The AI will call drift_contracts_list and report any issues.
Add custom API client patterns in .drift/config.json:
{
"contracts": {
"frontendPatterns": [
{
"name": "customClient",
"pattern": "myApi\\.(get|post|put|delete)\\(['\"]([^'\"]+)['\"]",
"methodGroup": 1,
"pathGroup": 2
}
],
"backendPatterns": [
{
"name": "customRouter",
"pattern": "router\\.(get|post)\\(['\"]([^'\"]+)['\"]",
"methodGroup": 1,
"pathGroup": 2
}
]
}
}{
"contracts": {
"ignorePaths": [
"/api/health",
"/api/metrics",
"/api/internal/*"
]
}
}Tell Drift about your standard response envelope:
{
"contracts": {
"responseEnvelope": {
"dataKey": "data",
"errorKey": "error",
"metaKey": "meta"
}
}
}Drift tracks contracts across language boundaries:
TypeScript Frontend βββ Python Backend
React App βββ Go API
Vue.js βββ Java Spring
Frontend (TypeScript):
const response = await fetch('/api/users');
const users: User[] = await response.json();Backend (Python/FastAPI):
@app.get("/api/users")
def get_users() -> List[UserResponse]:
return usersDrift verifies the TypeScript User type matches Python's UserResponse.
# Add to CI
drift scan --contracts
drift contracts check --fail-on mismatchDon't let mismatches accumulate. Fix them as they're discovered.
Strong typing helps Drift detect mismatches more accurately:
interface UserResponse {
user: User;
}
const response = await fetch('/api/users/123');
const data: UserResponse = await response.json();Configure ignore paths in .drift/config.json for endpoints that intentionally differ.
Use the MCP tool to review discovered contracts:
{
"status": "discovered"
}- Ensure both frontend and backend are scanned
- Check API patterns are recognized
- Add custom patterns if using non-standard clients
- Check if response envelope is configured correctly
- Verify type definitions are accurate
- Ignore intentional differences
- Check backend framework is supported
- Verify route files are not in
.driftignore - Add custom patterns for non-standard routers
- Constraints β Architectural invariants
- Quality Gates β Enforce contracts in CI
- Security Analysis β Data flow across APIs
- Cortex V2 Overview
- Memory Setup Wizard
- Memory CLI
- Universal Memory Types
- Learning System
- Token Efficiency
- Causal Graphs
- Code Generation
- Predictive Retrieval
- Architecture
- Call Graph Analysis
- Impact Analysis
- Security Analysis
- Data Boundaries
- Test Topology
- Coupling Analysis
- Error Handling Analysis
- Wrappers Detection
- Environment Variables
- Constants Analysis
- Styling DNA
- Constraints
- Contracts
- Decision Mining
- Speculative Execution
- Watch Mode
- Trends Analysis
- Projects Management
- Package Context
- Monorepo Support
- Reports & Export
- Dashboard
- 10 Languages
- 21 Frameworks
- 16 ORMs
- 400+ Detectors
- 50+ MCP Tools
- 60+ CLI Commands
- 23 Memory Types