Python Quick Start
Get ContractShield protecting your Python API in under 5 minutes.
Installation
# For FastAPIpip install contractshield[fastapi]
# For Flaskpip install contractshield[flask]FastAPI Setup
from fastapi import FastAPIfrom contractshield.fastapi import ContractShieldMiddleware
app = FastAPI()
# Add ContractShield middlewareapp.add_middleware( ContractShieldMiddleware, contracts_dir="./contracts", enable_vulnerability_scan=True,)
@app.post("/api/orders")async def create_order(order: dict): # Your handler - request is already validated return {"success": True}Flask Setup
from flask import Flaskfrom contractshield.flask import ContractShield
app = Flask(__name__)
# Initialize ContractShieldshield = ContractShield(app, contracts_dir="./contracts")
@app.route("/api/orders", methods=["POST"])def create_order(): # Your handler - request is already validated return {"success": True}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" } ]}Using OpenAPI Specs
ContractShield can auto-generate contracts from your OpenAPI specification:
app.add_middleware( ContractShieldMiddleware, openapi_path="./openapi.yaml", enable_vulnerability_scan=True,)CEL Invariants
Add business logic rules with CEL expressions:
from contractshield.decorators import cel_invariant
@app.post("/api/transfer")@cel_invariant( "request.body.amount <= context.user.balance", message="Insufficient balance")async def transfer(transfer: dict): return {"success": True}Pro Features
Activate Pro features with your license key:
app.add_middleware( ContractShieldMiddleware, contracts_dir="./contracts", license_key="your-license-key", learning_mode=True, # Auto-generate rules sink_protection=True, # RASP protection)Test It
# Valid requestcurl -X POST http://localhost:8000/api/orders \ -H "Content-Type: application/json" \ -d '{"items": ["product-1"], "total": 25.00}'
# Invalid request (rejected)curl -X POST http://localhost:8000/api/orders \ -H "Content-Type: application/json" \ -d '{"items": [], "total": 5.00}'Next Steps
- Define Contracts — JSON Schema and endpoint matching
- CEL Invariants — Business logic rules
- Deployment Options — Embedded, sidecar, or centralized