The user wants an "HTTP API semantic diff gate" implementation.
This involves three main components:
Breaking-change taxonomy: A classification system for what constitutes a "breaking change" in an API.
Exemptions: A mechanism to allow specific breaking changes to pass through the gate (e.g., for internal APIs, alpha versions, or strategic reasons).
Dashboards: Visualization/reporting to see the status of API changes over time or across services.
This is a complex system design and implementation request. I need to provide a conceptual architecture and then concrete code examples (likely in Python or Go, but Python is often more accessible for "logic" demonstrations, while Go is great for tooling; I'll stick to a conceptual design with Python-like pseudo-code or a mix of tools like openapi-diff).
Core Concept:
A "Semantic Diff Gate" sits in the CI/CD pipeline. It compares the new API specification (e.g., OpenAPI/Swagger) against a previous version (or a "golden" standard). It calculates the semantic differences (not just text diffs) and categorizes them based on the taxonomy. It then decides to pass or fail the build based on the rules and exemptions. Results are pushed to a dashboard.
Step 1: Breaking-Change Taxonomy
I need to define a hierarchy of changes.
Critical/Breaking (Fail):
Removing an endpoint.
Removing a parameter.
Changing a required parameter to optional (maybe? No, usually optional -> required is breaking. Required -> optional is safe). Wait, adding a required parameter is breaking. Changing data types (string to int).
Changing response structure (removing fields).
Non-Breaking/Compatible (Pass):
Adding an endpoint.
Adding an optional parameter.
Adding a field to a response.
Uncertain/Needs Review:
Changing descriptions.
I should structure this as a configuration file (YAML/JSON) that defines these rules.
Step 2: Implementation (The Gate Logic)
I need a script that:
Loads the Old Spec (base).
Loads the New Spec (head).
Uses a library to diff them. (e.g., openapi-diff or a custom Python script using prance or openapi-spec-validator). For a robust solution, mentioning an existing tool like oasdiff or openapi-diff is better than writing a parser from scratch. I will write a wrapper around oasdiff logic conceptually.
Applies the Taxonomy.
Checks Exemptions.
Outputs a result (Exit code 0 or 1).
Step 3: Exemptions
How to handle "I know this breaks, but do it anyway"?
A file in the repo (e.g., api-exemptions.json).
Structure: List of specific change types or paths that are allowed for this specific commit or PR.
Maybe hash-based exemption (allow this specific diff hash).
Step 4: Dashboards
We need to store the results.
Simple approach: JSON output uploaded to a static site or S3.
Better approach: A lightweight server (Flask/FastAPI) that receives webhooks from the CI pipeline with the diff data, stores it in a DB (SQLite/Postgres), and displays charts.
Dashboard Data:
Ingest the output of the gate (a JSON report) and visualize:
Total Changes vs Breaking Changes.
Trend over time.
Let's assemble the code.
Self-Correction during drafting: Writing a full semantic diff engine from scratch in one prompt is too long and error-prone. It's better to define the interface of the diff engine and mock the output, or use a simplified logic for demonstration. I will implement a mock diff function to demonstrate the gate logic, as the focus is on the "Gate" (Taxonomy + Exemptions), not parsing JSON schemas.
Plan:
Taxonomy Definition: Define standard rules (e.g., based on api-schema compatibility).
Diff Engine Wrapper: A class that takes two specs and returns structured changes.
Exemption Manager: Loads exemptions and filters changes.
Gate CLI: Main entry point.
Dashboard Generator: Python script to generate an HTML report.
Let's get coding.
This implementation defines a robust Semantic Diff Gate for CI/CD pipelines. It enforces API stability by comparing a proposed OpenAPI specification against a production baseline, classifying changes based on a breaking-change taxonomy, respecting exemptions, and generating a dashboard report.
1. Architecture Overview
The system consists of three main components:
Taxonomy & Configuration: YAML definitions of what constitutes a "breaking" change and where exemptions exist.
The Gate (Python): The core logic that parses specs, diffs the tree, applies rules, and determines pass/fail status.
The Dashboard: An HTML generator that visualizes the API diff history and current status.
2. Breaking-Change Taxonomy
We define our rules in a configuration file (taxonomy.yaml). This allows us to adjust severity levels without changing code.
yaml
# taxonomy.yaml
rules:
# High Severity: Will fail the build
breaking:
- id: api-removed
severity: error
description: "Removed endpoint"
- id: request-property-removed
severity: error
description: "Removed required request property"
- id: response-property-removed
severity: error
description: "Removed property from response schema"
- id: type-changed
severity: error
description: "Data type changed (e.g., string -> integer)"
- id: required-added
severity: error
description: "Added 'required' constraint to existing field"
# Low Severity: Warnings or Informational
non_breaking:
- id: api-added
severity: info
description: "New endpoint added"
- id: property-added
severity: info
description: "New optional property added"
- id: description-changed
severity: info
description: "Documentation updated"
exemptions:
# Allow specific breaking changes for specific paths/teams
- path: "/internal/experimental/*"
rule: "*"
reason: "Experimental endpoint"
expires: "2023-12-31"
- path: "/v1/users"
method: "GET"
rule: "response-property-removed"
reason: "Deprecation of PII field 'ssn'"
expires: "2024-01-01"
3. Implementation: The Semantic Diff Gate
This Python script acts as the CLI tool. It uses openapi-spec-validator and deepdiff concepts (simplified here for clarity) to compare specs.
Prerequisites: pip install pyyaml click deepdiff
python
4. Dashboard Implementation
The dashboard consumes the JSON reports generated by the gate to visualize the "Health" of the API lifecycle.
Dashboard Features:
Trend Graph: API Stability over time.
Change Feed: List of recent breaking vs. non-breaking changes.
Exemption Tracker: Visualizing how many technical debt items (exemptions) are active.
python
# dashboard.py
import json
import os
from jinja2 import Template
from datetime import datetime
# Simple HTML Template for the Dashboard
DASHBOARD_TEMPLATE = """
<!DOCTYPE html>
<html>
<head>
<title>API Semantic Diff Dashboard</title>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<style>
body { font-family: sans-serif; padding: 20px; background: #f5f5f5; }
.card { background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); margin-bottom: 20px; }
.fail { color: #d32f2f; }
.pass { color: #388e3c; }
.exempt { color: #f57c00; }
table { width: 100%; border-collapse: collapse; margin-top: 10px; }
th, td { text-align: left; padding: 8px; border-bottom: 1px solid #ddd; }
</style>
</head>
<body>
<h1>API Governance Dashboard</h1>
<div class="card">
<h2>Stability Trend (Last 7 Days)</h2>
<div id="trendChart"></div>
</div>
<div class="card">
<h2>Recent Changes (Latest Run)</h2>
<table>
<thead>
<tr>
<th>Status</th>
<th>Rule</th>
<th>Path</th>
<th>Severity</th>
</tr>
</thead>
<tbody>
{% for item in findings %}
<tr class="{{ item.status.lower() }}">
<td><strong>{{ item.status }}</strong></td>
<td>{{ item.rule_id }}</td>
<td style="font-family: monospace; font-size: 0.9em;">{{ item.path | truncate(60) }}</td>
<td>{{ item.severity }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</body>
</html>
"""
class DashboardGenerator:
def __init__(self, report_path):
with open(report_path, 'r') as f:
self.data = json.load(f)
def generate_html(self, output_file="dashboard/index.html"):
# Prepare data for template
template = Template(DASHBOARD_TEMPLATE)
# Simulate historical data for the chart
days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
failures = [0, 2, 1, 0, self.data['summary']['failures'], 0, 0]
html_content = template.render(
findings=self.data['findings'],
chart_days=days,
chart_failures=failures
)
os.makedirs("dashboard", exist_ok=True)
with open(output_file, "w") as f:
f.write(html_content)
print(f"Dashboard generated at {output_file}")
# Usage logic (typically called after gate.py runs)
if __name__ == "__main__":
# In a real scenario, you would aggregate multiple reports
gen = DashboardGenerator("report.json")
gen.generate_html()
5. Integration Strategy
To make this effective, integrate it into your CI pipeline (e.g., GitHub Actions).
Deploy Dashboard: Run dashboard.py and publish to GitHub Pages or internal wiki.
6. Exemption Management Strategy
Exemptions are technical debt. To prevent abuse:
Require Expiry: No permanent exemptions. Forces periodic review.
Require Reason: Must link to a Ticket/Issue ID.
Scope Narrowly: Exempt specific paths or rules, never blanket exemptions unless necessary.
# gate.py
import yaml
import json
import click
from deepdiff import DeepDiff
from datetime import datetime
class APIDiffGate:
def __init__(self, taxonomy_path):
with open(taxonomy_path, 'r') as f:
self.config = yaml.safe_load(f)
self.taxonomy = self.config['rules']
self.exemptions = self.config.get('exemptions', [])
def load_spec(self, path):
with open(path, 'r') as f:
return yaml.safe_load(f)
def check_exemption(self, change_path, rule_id):
"""Check if a specific change is exempted."""
for exemption in self.exemptions:
# Check expiry
if datetime.now() > datetime.strptime(exemption['expires'], "%Y-%m-%d"):
continue
# Simple wildcard matching logic
if exemption['rule'] == '*' or exemption['rule'] == rule_id:
if exemption['path'].replace('*', '') in change_path:
return True
return False
def classify_change(self, diff_item):
"""
Maps a raw diff to a Taxonomy Rule ID.
This is a simplified heuristic logic.
"""
# Logic: If a key is removed -> Removal
if 'values_changed' in diff_item:
return "type-changed" # Simplified
if 'iterable_item_removed' in diff_item or 'dictionary_item_removed' in diff_item:
path = str(diff_item.get('path', ''))
if 'paths' in path:
return "api-removed"
return "response-property-removed"
if 'iterable_item_added' in diff_item or 'dictionary_item_added' in diff_item:
return "property-added"
return "unknown"
def run_analysis(self, old_spec_path, new_spec_path):
old_spec = self.load_spec(old_spec_path)
new_spec = self.load_spec(new_spec_path)
# DeepDiff provides the structural differences
diff = DeepDiff(old_spec, new_spec, ignore_order=True)
findings = []
is_blocking = False
# Process Diffs
for change_type, changes in diff.items():
for change in changes:
# 1. Identify what happened
rule_id = self.classify_change({change_type: change})
# 2. Look up severity in Taxonomy
rule_def = next((r for r in self.taxonomy['breaking'] if r['id'] == rule_id), None)
if not rule_def:
rule_def = next((r for r in self.taxonomy['non_breaking'] if r['id'] == rule_id), {'severity': 'info'})
# 3. Check Exemptions
is_exempt = self.check_exemption(str(change), rule_id)
status = "PASS"
if rule_def['severity'] == 'error':
if is_exempt:
status = "EXEMPT"
else:
status = "FAIL"
is_blocking = True
findings.append({
"rule_id": rule_id,
"severity": rule_def['severity'],
"description": rule_def.get('description', ''),
"path": str(change),
"status": status,
"exempt_reason": "Allowed via config" if is_exempt else None
})
return {
"is_blocking": is_blocking,
"findings": findings,
"summary": {
"total": len(findings),
"failures": len([f for f in findings if f['status'] == 'FAIL'])
}
}
@click.command()
@click.option('--old', required=True, help='Path to baseline (production) spec')
@click.option('--new', required=True, help='Path to proposed (PR) spec')
@click.option('--taxonomy', default='taxonomy.yaml', help='Path to taxonomy config')
@click.option('--report', default='report.json', help='Output report path')
def cli(old, new, taxonomy, report):
gate = APIDiffGate(taxonomy)
result = gate.run_analysis(old, new)
with open(report, 'w') as f:
json.dump(result, f, indent=2)
print(f"Analysis Complete. Blocking: {result['is_blocking']}")
if result['is_blocking']:
print("::error::Breaking changes detected without exemption.")
exit(1)
else:
print("::notice::API changes compliant.")
exit(0)
if __name__ == '__main__':
cli()