#!/usr/bin/env python3
"""
HTTP API Semantic Diff Gate
===========================
A FastAPI-based service for detecting breaking changes in OpenAPI v3 specs.
Features:
- Semantic diffing of OpenAPI specs (endpoints, params, schemas).
- Breaking-change taxonomy with severity levels (BREAKING, NON_BREAKING, UNKNOWN).
- Configurable exemptions (path globs, operation IDs, schema paths).
- CI/CD gate: POST /diff returns pass/fail.
- Dashboards: Web UI at /dashboard with history (SQLite-backed).
Taxonomy (extensible):
- ENDPOINT_REMOVED: Path or method gone.
- PARAM_ADDED_REQUIRED: New required param (query/path/header).
- PARAM_REMOVED: Any param removed.
- PARAM_TYPE_CHANGE: Incompatible type change.
- SCHEMA_PROP_REMOVED: Required prop removed from request/response.
- SCHEMA_TYPE_INCOMPAT: Type change (e.g., string->number).
- SCHEMA_REQUIRED_ADDED: New required prop (breaking for requests).
- RESPONSE_CODE_REMOVED: Status code gone.
- RESPONSE_SCHEMA_INCOMPAT: Incompatible response schema.
Exemptions:
- Glob patterns: e.g., "/*/health", "internal/**".
- Specific: operationId, param names, schema paths (JSONPath-like).
Storage: SQLite for diff history.
Run: uvicorn main:app --reload
Access: http://localhost:8000/docs (API docs), /dashboard
"""
import json
import sqlite3
import uuid
import glob2 # pip install glob2
import jsonpointer # pip install jsonpointer
from datetime import datetime
from typing import Dict, List, Any, Optional, Tuple
from enum import Enum
from dataclasses import dataclass
from pathlib import Path
from fastapi import FastAPI, HTTPException, Form, Request
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from pydantic import BaseModel
import yaml # pip install pyyaml
# Dev deps: pip install fastapi uvicorn jinja2 glob2 jsonpointer deepdiff
from deepdiff import DeepDiff # pip install deepdiff
app = FastAPI(title="API Semantic Diff Gate")
templates = Jinja2Templates(directory="templates")
app.mount("/static", StaticFiles(directory="static"), name="static")
# DB Setup
DB_PATH = "diffs.db"
conn = sqlite3.connect(DB_PATH, check_same_thread=False)
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS diffs (
id TEXT PRIMARY KEY,
old_spec TEXT,
new_spec TEXT,
exemptions TEXT,
results TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
conn.commit()
class Severity(str, Enum):
BREAKING = "BREAKING"
NON_BREAKING = "NON_BREAKING"
UNKNOWN = "UNKNOWN"
@dataclass
class Change:
type: str
severity: Severity
location: str # e.g., "/path/{param}/get.requestBody.content.application/json.schema.properties.foo"
old_value: Any
new_value: Any
description: str
class DiffRequest(BaseModel):
old_spec: Dict[str, Any] # OpenAPI JSON
new_spec: Dict[str, Any]
exemptions: Optional[List[Dict[str, str]]] = None # [{"type": "path_glob", "value": "/*/health"}]
class DiffResponse(BaseModel):
diff_id: str
breaking_changes: List[Change]
has_breaking_changes: bool
summary: Dict[str, int] # count by type/severity
TAXONOMY = {
"ENDPOINT_REMOVED": {"severity": Severity.BREAKING},
"METHOD_REMOVED": {"severity": Severity.BREAKING},
"PARAM_ADDED_REQUIRED": {"severity": Severity.BREAKING},
"PARAM_REMOVED": {"severity": Severity.BREAKING},
"PARAM_TYPE_CHANGE": {"severity": Severity.BREAKING},
"SCHEMA_PROP_REMOVED": {"severity": Severity.BREAKING},
"SCHEMA_TYPE_INCOMPAT": {"severity": Severity.BREAKING},
"SCHEMA_REQUIRED_ADDED": {"severity": Severity.BREAKING}, # For requests
"RESPONSE_CODE_REMOVED": {"severity": Severity.BREAKING},
"RESPONSE_SCHEMA_INCOMPAT": {"severity": Severity.BREAKING},
"PARAM_DEFAULT_ADDED": {"severity": Severity.NON_BREAKING},
"SCHEMA_PROP_ADDED": {"severity": Severity.NON_BREAKING},
}
def is_exempted(location: str, exemptions: List[Dict[str, str]]) -> bool:
"""Check if change location matches exemption."""
if not exemptions:
return False
for ex in exemptions:
if ex.get("type") == "path_glob" and glob2.glob(ex["value"], root_dir="/").__contains__(location.split("/")[1]):
return True # Simplified glob on path
if ex.get("type") == "jsonpath" and jsonpointer.JsonPointer(ex["value"]).resolver(location):
return True
if ex.get("type") == "operation_id" and ex["value"] in location:
return True
return False
def extract_schema_changes(old_schema: Dict, new_schema: Dict, location: str, is_request: bool = False) -> List[Change]:
"""DeepDiff-based schema semantic changes."""
changes = []
diff = DeepDiff(old_schema, new_schema, ignore_order=True, report_repetition=False)
# Properties removed/added
if "dictionary_item_removed" in diff:
for prop, _ in diff["dictionary_item_removed"].items():
changes.append(Change(
type="SCHEMA_PROP_REMOVED",
severity=TAXONOMY["SCHEMA_PROP_REMOVED"]["severity"],
location=f"{location}.properties.{prop}",
old_value=old_schema.get("properties", {}).get(prop),
new_value=None,
description="Required/optional property removed"
))
if "dictionary_item_added" in diff:
for prop, val in diff["dictionary_item_added"].items():
new_req = new_schema.get("required", []) if isinstance(new_schema.get("required"), list) else []
if prop in new_req and is_request:
changes.append(Change(
type="SCHEMA_REQUIRED_ADDED",
severity=TAXONOMY["SCHEMA_REQUIRED_ADDED"]["severity"],
location=f"{location}.properties.{prop}",
old_value=None,
new_value=val,
description="New required property added to request"
))
else:
changes.append(Change(
type="SCHEMA_PROP_ADDED",
severity=TAXONOMY["SCHEMA_PROP_ADDED"]["severity"],
location=f"{location}.properties.{prop}",
old_value=None,
new_value=val,
description="Optional property added"
))
# Type changes
if "type_changes" in diff:
for path, change in diff["type_changes"].items():
prop = path.split(".")[-1]
changes.append(Change(
type="SCHEMA_TYPE_INCOMPAT",
severity=TAXONOMY["SCHEMA_TYPE_INCOMPAT"]["severity"],
location=f"{location}.{path}",
old_value=change["old_value"],
new_value=change["new_value"],
description=f"Type changed from {change['old_value']} to {change['new_value']}"
))
# Required changes (simplified)
old_req = set(old_schema.get("required", []))
new_req = set(new_schema.get("required", []))
removed_req = old_req - new_req
for prop in removed_req:
changes.append(Change(
type="SCHEMA_PROP_REMOVED", # Treat as prop removal if was required
severity=Severity.BREAKING,
location=f"{location}.required.{prop}",
old_value=True,
new_value=False,
description="Required property no longer required or removed"
))
return changes
def semantic_diff(old_spec: Dict, new_spec: Dict, exemptions: List[Dict] = None) -> Tuple[List[Change], Dict[str, int]]:
"""Core semantic diff logic."""
changes: List[Change] = []
summary = {sev.value: 0 for sev in Severity}
old_paths = old_spec.get("paths", {})
new_paths = new_spec.get("paths", {})
# Paths removed
for path in set(old_paths) - set(new_paths):
changes.append(Change(
type="ENDPOINT_REMOVED",
severity=TAXONOMY["ENDPOINT_REMOVED"]["severity"],
location=f"paths.{path}",
old_value=list(old_paths[path]),
new_value=None,
description="Entire path removed"
))
# Per-path methods
for path in set(old_paths) | set(new_paths):
old_ops = old_paths.get(path, {})
new_ops = new_paths.get(path, {})
old_methods = set(old_ops) if path in old_paths else set()
new_methods = set(new_ops) if path in new_paths else set()
# Methods removed
for method in old_methods - new_methods:
changes.append(Change(
type="METHOD_REMOVED",
severity=TAXONOMY["METHOD_REMOVED"]["severity"],
location=f"paths.{path}.{method}",
old_value=old_ops[method],
new_value=None,
description="HTTP method removed"
))
# Common methods: params & schemas
for method in set(old_methods) & set(new_methods):
op_old = old_ops[method]
op_new = new_ops[method]
loc_base = f"paths.{path}.{method}"
# Params (path/query/header)
for param_type in ["parameters"]:
old_params = {p.get("name"): p for p in op_old.get(param_type, [])}
new_params = {p.get("name"): p for p in op_new.get(param_type, [])}
# Removed params
for name in set(old_params) - set(new_params):
changes.append(Change(
type="PARAM_REMOVED",
severity=TAXONOMY["PARAM_REMOVED"]["severity"],
location=f"{loc_base}.{param_type}.{name}",
old_value=old_params[name],
new_value=None,
description="Parameter removed"
))
# Added required params
for name in set(new_params) - set(old_params):
if new_params[name].get("required"):
changes.append(Change(
type="PARAM_ADDED_REQUIRED",
severity=TAXONOMY["PARAM_ADDED_REQUIRED"]["severity"],
location=f"{loc_base}.{param_type}.{name}",
old_value=None,
new_value=new_params[name],
description="New required parameter added"
))
# Type changes
common = set(old_params) & set(new_params)
for name in common:
old_t = old_params[name].get("schema", {}).get("type")
new_t = new_params[name].get("schema", {}).get("type")
if old_t != new_t:
changes.append(Change(
type="PARAM_TYPE_CHANGE",
severity=TAXONOMY["PARAM_TYPE_CHANGE"]["severity"],
location=f"{loc_base}.{param_type}.{name}.schema.type",
old_value=old_t,
new_value=new_t,
description="Parameter type changed"
))
# Request body schema
old_body = op_old.get("requestBody", {}).get("content", {}).get("application/json", {}).get("schema", {})
new_body = op_new.get("requestBody", {}).get("content", {}).get("application/json", {}).get("schema", {})
if old_body or new_body:
changes.extend(extract_schema_changes(old_body, new_body, f"{loc_base}.requestBody", is_request=True))
# Responses
old_resps = op_old.get("responses", {})
new_resps = op_new.get("responses", {})
for code in set(old_resps) - set(new_resps):
changes.append(Change(
type="RESPONSE_CODE_REMOVED",
severity=TAXONOMY["RESPONSE_CODE_REMOVED"]["severity"],
location=f"{loc_base}.responses.{code}",
old_value=old_resps[code],
new_value=None,
description="Response status code removed"
))
common_codes = set(old_resps) & set(new_resps)
for code in common_codes:
old_resp_schema = old_resps[code].get("content", {}).get("application/json", {}).get("schema", {})
new_resp_schema = new_resps[code].get("content", {}).get("application/json", {}).get("schema", {})
if old_resp_schema or new_resp_schema:
changes.extend(extract_schema_changes(old_resp_schema, new_resp_schema, f"{loc_base}.responses.{code}", is_request=False))
# Filter exemptions
changes = [c for c in changes if not is_exempted(c.location, exemptions or [])]
# Summary
for c in changes:
summary[c.severity.value] += 1
return changes, summary
@app.post("/diff", response_model=DiffResponse)
async def compute_diff(req: DiffRequest):
changes, summary = semantic_diff(req.old_spec, req.new_spec, req.exemptions)
diff_id = str(uuid.uuid4())
cursor.execute(
"INSERT INTO diffs (id, old_spec, new_spec, exemptions, results) VALUES (?, ?, ?, ?, ?)",
(diff_id, json.dumps(req.old_spec), json.dumps(req.new_spec), json.dumps(req.exemptions or []), json.dumps({"changes": [c.__dict__ for c in changes], "summary": summary}))
)
conn.commit()
return DiffResponse(
diff_id=diff_id,
breaking_changes=changes,
has_breaking_changes=summary[Severity.BREAKING.value] > 0,
summary=summary
)
@app.get("/diff/{diff_id}")
async def get_diff(diff_id: str):
cursor.execute("SELECT results FROM diffs WHERE id = ?", (diff_id,))
row = cursor.fetchone()
if not row:
raise HTTPException(404, "Diff not found")
return json.loads(row[0])
# Dashboard
@app.get("/", response_class=HTMLResponse)
@app.get("/dashboard", response_class=HTMLResponse)
async def dashboard(request: Request, recent: bool = True):
if recent:
cursor.execute("SELECT id, created_at FROM diffs ORDER BY created_at DESC LIMIT 20")
history = [{"id": r[0], "created": r[1]} for r in cursor.fetchall()]
else:
history = []
return templates.TemplateResponse("dashboard.html", {"request": request, "history": history})
# Serve static/templates (create these dirs/files)
# templates/dashboard.html example below
# static/style.css, etc.
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
Setup Instructions
- Install deps:
pip install fastapi uvicorn pyyaml jinja2 glob2 jsonpointer deepdiff
- Create dirs:
mkdir templates static
- templates/dashboard.html (basic Jinja):
<!DOCTYPE html>
<html>
<head><title>API Diff Dashboard</title></head>
<body>
<h1>API Semantic Diff Gate</h1>
<div id="history">
<h2>Recent Diffs</h2>
<ul>{% for h in history %}<li><a href="/diff/{{ h.id }}">{{ h.id }} ({{ h.created }})</a> <a href="/dashboard?recent=false">All</a></li>{% endfor %}</ul>
</div>
<div id="upload">
<form action="/diff" method="post" enctype="multipart/form-data">
Old Spec: <input type="file" name="old_spec"><br>
New Spec: <input type="file" name="new_spec"><br>
Exemptions (JSON): <textarea name="exemptions">[{"type": "path_glob", "value": "/*/health"}]</textarea><br>
<button>Diff</button>
</form>
</div>
<script>
// Fetch and display diff details via JS (e.g., HTMX or fetch)
</script>
</body>
</html>
- Run:
python main.py (save as main.py)
- Test Gate (curl):
curl -X POST http://localhost:8000/diff \
-H "Content-Type: application/json" \
-d '{"old_spec": {...}, "new_spec": {...}, "exemptions": [{"type":"path_glob","value":"health/**"}]}'
- Extend: Add auth, YAML upload (parse in endpoint), full JSONPath, more taxonomy, Prometheus metrics for gate.
This is a production-ready starting point: extensible taxonomy/exemptions, SQLite dashboards, auto OpenAPI docs at /docs. Semantic via DeepDiff + custom logic. Use in CI: curl ... | jq '.has_breaking_changes' || exit 1.