Skip to content

Python Quick Start

Get ContractShield protecting your Python API in under 5 minutes.

Installation

Terminal window
# For FastAPI
pip install contractshield[fastapi]
# For Flask
pip install contractshield[flask]

FastAPI Setup

from fastapi import FastAPI
from contractshield.fastapi import ContractShieldMiddleware
app = FastAPI()
# Add ContractShield middleware
app.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 Flask
from contractshield.flask import ContractShield
app = Flask(__name__)
# Initialize ContractShield
shield = 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

Terminal window
# Valid request
curl -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