Skip to content

Quick Start

Get ContractShield protecting your API in under 5 minutes.

Installation

Terminal window
npm install @cshield/pep-express
# or
npm install @cshield/pep-fastify

Express Setup

import express from 'express';
import { contractShield } from '@cshield/pep-express';
const app = express();
app.use(express.json());
// Load contracts from directory
app.use(contractShield({
contractsDir: './contracts',
}));
app.post('/api/orders', (req, res) => {
// Your handler - request is already validated
res.json({ success: true });
});
app.listen(3000);

Fastify Setup

import Fastify from 'fastify';
import { contractShieldPlugin } from '@cshield/pep-fastify';
const app = Fastify();
app.register(contractShieldPlugin, {
contractsDir: './contracts',
});
app.post('/api/orders', async (req, reply) => {
return { success: true };
});
app.listen({ port: 3000 });

Your First Contract

Create contracts/orders.json:

{
"endpoint": "/api/orders",
"method": "POST",
"schema": {
"type": "object",
"properties": {
"items": {
"type": "array",
"items": { "type": "string" },
"minItems": 1
},
"total": {
"type": "number",
"minimum": 0
}
},
"required": ["items", "total"]
},
"invariants": [
{
"expr": "request.body.total >= 10.00",
"message": "Minimum order value is $10"
}
]
}

Test It

Terminal window
# Valid request
curl -X POST http://localhost:3000/api/orders \
-H "Content-Type: application/json" \
-d '{"items": ["product-1"], "total": 25.00}'
# Invalid request (rejected)
curl -X POST http://localhost:3000/api/orders \
-H "Content-Type: application/json" \
-d '{"items": [], "total": 5.00}'

Next Steps