fastapi-contractguard 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
File without changes
contractguard/cli.py ADDED
@@ -0,0 +1,159 @@
1
+ import typer
2
+ import json
3
+ from pathlib import Path
4
+ from contractguard.openapi import generate_openapi
5
+ from contractguard.comparator import compare_contracts
6
+ from contractguard.docs import show_contract_docs
7
+ app = typer.Typer(
8
+ name="contractguard",
9
+ help="[yellow]Now Pratham Detects [bold bright_magenta]breaking changes[/bold bright_magenta] in API Contracts | Please use command --docs for more information",
10
+ rich_markup_mode="rich"
11
+ )
12
+
13
+ @app.command("docs")
14
+ def show_docs():
15
+ """Show ContractGuard documentation."""
16
+
17
+ show_contract_docs()
18
+
19
+ @app.command("init")
20
+ def init(app_path:str=typer.Option(...,"--app")):
21
+ """Initialize ContractGuard in the current project."""
22
+ try:
23
+ typer.echo("Loading FastAPI application....")
24
+
25
+ schema = generate_openapi(app_path)
26
+ folder = Path('.contractguard')
27
+ folder.mkdir(exist_ok=True)
28
+
29
+ print(f"Scehama : {schema}")
30
+ # schema["paths"]["path"]["description"]
31
+ baseline = folder / "baseline.json"
32
+
33
+
34
+ paths = schema.get("paths",{})
35
+
36
+ protected_routes = []
37
+ for path,methods in paths.items():
38
+ for method,details in methods.items():
39
+ if "protect" in details.get("description","").lower():
40
+ details["is_protected"]=True
41
+ else:
42
+ details["is_protected"]=False
43
+
44
+ with open(baseline,"w",encoding="utf-8") as file:
45
+ json.dump(schema,file,indent=2)
46
+
47
+ typer.echo("✓ FastAPI app loaded")
48
+ typer.echo("✓ OpenAPI schema generated")
49
+ typer.echo(f"✓ Baseline saved: {baseline}")
50
+
51
+ except Exception as error:
52
+ typer.echo(f"✗ Error: {error}", err=True)
53
+ raise typer.Exit(code=1)
54
+
55
+
56
+ @app.command("say-hi")
57
+ def sayhi():
58
+ """Say Hi as a test message"""
59
+ typer.echo("Hello from contractguard")
60
+
61
+
62
+ @app.command("check")
63
+ def check(app_path:str = typer.Option(...,"--app",help="FastAPI application path . eg: main:app")):
64
+ """Comparator logic : heart"""
65
+
66
+ try:
67
+ baseline_path = Path(".contractguard/baseline.json")
68
+
69
+ #check if baseline is there:
70
+ if not baseline_path.exists():
71
+ typer.echo("No baseline found. Please run `init` first")
72
+ raise typer.Exit(code=1)
73
+
74
+ protected_routes = []
75
+
76
+ # else load the basline
77
+ with open(baseline_path,"r",encoding="utf-8") as file:
78
+ old_contract = json.load(file)
79
+
80
+ typer.echo("Loading the FastAPI application...")
81
+ new_contract = generate_openapi(app_path)
82
+
83
+ #Compare the paths
84
+ changes = compare_contracts(old_contract,new_contract)
85
+
86
+ typer.echo("Changes in the contracts :\n")
87
+
88
+ if not changes:
89
+ typer.echo(
90
+ "No changes beem occurred | "
91
+ )
92
+
93
+ for change in changes:
94
+ typer.echo(f"\nchange value : {change}")
95
+
96
+ if change["severity"] == "breaking":
97
+ icon = "🔴"
98
+ label = 'BREAKING CHANGE'
99
+ else:
100
+ icon = "🟢"
101
+ label = "SAFE CHANGE"
102
+
103
+ method = change.get("method")
104
+
105
+ if method:
106
+ endpoint = (
107
+ f"{method} {change['path']}"
108
+ )
109
+ else:
110
+ endpoint = change['path']
111
+
112
+ typer.echo(
113
+ f"{icon} {label}: "
114
+ f"{endpoint}"
115
+ )
116
+
117
+ except Exception as error:
118
+ typer.echo(
119
+ f"✗ Failed to check API contract: {error}",
120
+ err=True,
121
+ )
122
+
123
+ raise typer.Exit(code=1)
124
+
125
+
126
+ @app.command("update")
127
+ def update(
128
+ app_path:str=typer.Option(
129
+ ...,
130
+ "--app",
131
+ help="To update the baseline Eg.main:app"
132
+ )
133
+ ):
134
+
135
+ """Updating the openapi.json"""
136
+
137
+ try:
138
+ typer.echo("Generating the current Current API contract...")
139
+
140
+ openapi_schema = generate_openapi(app_path=app_path)
141
+ print("Got the protected route info : ",openapi_schema[""])
142
+ print(f"OPEN API SCHEMA : \n",openapi_schema)
143
+ contractguard_path=Path('.contractguard')
144
+ contractguard_path.mkdir(exist_ok=True)
145
+
146
+ baseline_path = contractguard_path / "baseline.json"
147
+
148
+ with open(baseline_path,"w",encoding="utf-8") as file:
149
+ json.dump(openapi_schema,file,indent=2)
150
+
151
+ typer.echo(f"✓ API baseline updated: {baseline_path}")
152
+
153
+ except Exception as e:
154
+ typer.echo(
155
+ f"✗ Failed to update baseline: {e}",
156
+ err=True,
157
+ )
158
+ if __name__ == "__main__":
159
+ app()
@@ -0,0 +1,61 @@
1
+ def compare_contracts(old: dict, new: dict):
2
+ changes = []
3
+
4
+ old_paths = old.get("paths", {})
5
+ new_paths = new.get("paths", {})
6
+
7
+ # --------------------------------
8
+ # Check removed endpoints / methods
9
+ # --------------------------------
10
+
11
+ for path, old_methods in old_paths.items():
12
+ print("Path ",old_paths)
13
+ # Entire endpoint was removed
14
+ if path not in new_paths:
15
+ changes.append({
16
+ "type": "removed_endpoint",
17
+ "path": path,
18
+ "severity": "breaking",
19
+ })
20
+
21
+ continue
22
+
23
+ # Check if individual HTTP methods were removed
24
+ for method in old_methods:
25
+
26
+ if method not in new_paths[path]:
27
+ changes.append({
28
+ "type": "removed_endpoint",
29
+ "path": path,
30
+ "method": method.upper(),
31
+ "severity": "breaking",
32
+ })
33
+
34
+ # --------------------------------
35
+ # Check added endpoints / methods
36
+ # --------------------------------
37
+
38
+ for path, new_methods in new_paths.items():
39
+
40
+ # Entire endpoint was added
41
+ if path not in old_paths:
42
+ changes.append({
43
+ "type": "added_endpoint",
44
+ "path": path,
45
+ "severity": "safe",
46
+ })
47
+
48
+ continue
49
+
50
+ # Check if individual HTTP methods were added
51
+ for method in new_methods:
52
+
53
+ if method not in old_paths[path]:
54
+ changes.append({
55
+ "type": "added_endpoint",
56
+ "path": path,
57
+ "method": method.upper(),
58
+ "severity": "safe",
59
+ })
60
+
61
+ return changes
@@ -0,0 +1,17 @@
1
+ from pathlib import Path
2
+ import tomllib
3
+
4
+
5
+ def load_config():
6
+ config_path = Path("contractguard.toml")
7
+
8
+ if not config_path.exists():
9
+ raise FileNotFoundError(
10
+ "contractguard.toml not found !"
11
+ "Run `contractguard init` from your FastAPI project."
12
+ )
13
+
14
+ with open(config_path,"rb") as file:
15
+ config = tomllib.load(file)
16
+
17
+ return config
contractguard/docs.py ADDED
@@ -0,0 +1,50 @@
1
+ import typer
2
+
3
+ def show_contract_docs():
4
+ typer.echo("")
5
+ typer.secho(
6
+ "CONTRACTGUARD",
7
+ fg=typer.colors.YELLOW,
8
+ bold=True,
9
+ )
10
+
11
+ typer.echo(
12
+ "\nContractGuard detects breaking changes "
13
+ "in FastAPI API contracts."
14
+ )
15
+
16
+ typer.echo("\nCOMMANDS")
17
+ typer.echo(" init Create the initial API baseline")
18
+ typer.echo(" check Check the current API against the baseline")
19
+ typer.echo(" update Update the approved API baseline")
20
+ typer.echo(" docs Show ContractGuard documentation")
21
+
22
+ typer.echo("\nWORKFLOW")
23
+ typer.echo(" 1. Initialize the baseline")
24
+ typer.echo(" 2. Modify your FastAPI API")
25
+ typer.echo(" 3. Run check")
26
+ typer.echo(" 4. Review the detected changes")
27
+ typer.echo(" 5. Run update when the changes are approved")
28
+
29
+ typer.echo("\nPROTECTED ROUTES")
30
+ typer.echo(
31
+ ' If a route must be strictly protected, '
32
+ 'include the word "protected" in the route docstring.'
33
+ )
34
+
35
+ typer.echo("\nEXAMPLE")
36
+ typer.echo(
37
+ ' @app.get("/users", description="protected")'
38
+ )
39
+ typer.echo("\nEXAMPLES")
40
+ typer.echo(
41
+ " contractguard init --app main:app"
42
+ )
43
+ typer.echo(
44
+ " contractguard check --app main:app"
45
+ )
46
+ typer.echo(
47
+ " contractguard update --app main:app"
48
+ )
49
+
50
+ typer.echo("")
@@ -0,0 +1,21 @@
1
+ import importlib
2
+
3
+ def load_fastapi_app(app_path:str):
4
+
5
+ if ":" not in app_path:
6
+ raise ValueError(
7
+ "Invalid app path. Use the format `module:app`, "
8
+ "for eg. `main:app` "
9
+ )
10
+ module_name,app_name = app_path.split(":",1)
11
+
12
+ module = importlib.import_module(module_name)
13
+ print("MAIN MODULE LOADED FROM:", module.__file__)
14
+ app = getattr(module,app_name)
15
+ print("Returning app value : (load_fast_api) function : ",app)
16
+ return app
17
+
18
+ def generate_openapi(app_path:str):
19
+ app = load_fastapi_app(app_path=app_path)
20
+
21
+ return app.openapi()
File without changes
@@ -0,0 +1,55 @@
1
+ Metadata-Version: 2.4
2
+ Name: fastapi-contractguard
3
+ Version: 0.1.0
4
+ Summary: Detect breaking changes in FastAPI API contracts
5
+ Author: Prathamesh Pai
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/PrathamPai2004/contractguard
8
+ Project-URL: Repository, https://github.com/PrathamPai2004/contractguard
9
+ Requires-Python: >=3.10
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Requires-Dist: fastapi>=0.115.0
13
+ Requires-Dist: typer>=0.12.0
14
+ Dynamic: license-file
15
+
16
+
17
+ # ContractGuard
18
+
19
+ ContractGuard is a developer tool for **FastAPI applications** that helps you detect and manage API contract changes.
20
+
21
+ It generates your application's OpenAPI schema, stores a baseline contract, and compares future changes against that baseline so you can identify breaking API changes before they reach production.
22
+
23
+ ## Why ContractGuard?
24
+
25
+ APIs evolve constantly.
26
+
27
+ You add a new endpoint, rename a response field, change a parameter, modify a request body, or remove an endpoint.
28
+
29
+ The problem is that some of these changes can silently break existing clients.
30
+
31
+ ContractGuard helps you answer:
32
+
33
+ > "Did my API contract change?"
34
+
35
+ and more importantly:
36
+
37
+ > "Did I accidentally introduce a breaking change?"
38
+
39
+ ---
40
+
41
+ ## Features
42
+
43
+ - Generate OpenAPI schema from a FastAPI application
44
+ - Initialize an API contract baseline
45
+ - Compare the current API schema with the stored contract
46
+ - Detect API contract changes
47
+ - Check contracts from the command line
48
+ - Update the stored contract after intentional changes
49
+ - Generate API documentation
50
+ - Designed specifically for FastAPI projects
51
+ - Simple CLI workflow
52
+
53
+ ---
54
+
55
+ -- TO BE LAUNCHED SOON
@@ -0,0 +1,13 @@
1
+ contractguard/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ contractguard/cli.py,sha256=pLamvR-wEKCDI7P0ltBm_uGpPfg_FvCVv9Oct0wC57k,4713
3
+ contractguard/comparator.py,sha256=DtnMDWfPNDyl2J8K368u2vpvvELZpq8AJbjljvcyYTs,1798
4
+ contractguard/config.py,sha256=eszYeDbrans6W906JeeajXawnjhpGsrQ8dDqchLdNWg,414
5
+ contractguard/docs.py,sha256=kI67_oIhAzW0CFoAk7ofbdOeER1Q_6-R8NxVGGy_Vwg,1414
6
+ contractguard/openapi.py,sha256=578kMSGalPMUAt4BBfB4vL2jsNuI-no0ReIgQ7anjFc,615
7
+ contractguard/reporter.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ fastapi_contractguard-0.1.0.dist-info/licenses/LICENSE,sha256=LyYAVGiSH06xTPDqs10vRxAu1fHd0R9Jr0QXwvsbVpA,1090
9
+ fastapi_contractguard-0.1.0.dist-info/METADATA,sha256=tzhCl13mSRpDcp_8D6sICIF3NjPZQ9lLTLETWok5Ygk,1677
10
+ fastapi_contractguard-0.1.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
11
+ fastapi_contractguard-0.1.0.dist-info/entry_points.txt,sha256=t68aIpNGxtxPgBs7t05Uo6T_ntqt1iMtx27hz95mHmw,56
12
+ fastapi_contractguard-0.1.0.dist-info/top_level.txt,sha256=BqCNKdN75bKV6kkU52_jIfpgTxOGcmNYgSnY9ZqKX18,14
13
+ fastapi_contractguard-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ contractguard = contractguard.cli:app
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Prathamesh Pai
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ contractguard