|
| 1 | +import importlib |
| 2 | +import os |
| 3 | +import httpx |
| 4 | +from fastapi import FastAPI |
| 5 | + |
| 6 | +# Adjust this to your actual app import path: |
| 7 | +app_module = "zotify_api.main" |
| 8 | +app_attr = "app" |
| 9 | +BASE_URL = "http://127.0.0.1:8000" |
| 10 | + |
| 11 | + |
| 12 | +def main(): |
| 13 | + """ |
| 14 | + Dynamically imports the FastAPI app, discovers all GET routes that |
| 15 | + don't require path parameters, and then sends a request to each one |
| 16 | + to check its status. |
| 17 | + """ |
| 18 | + print(f"--- Starting API Audit for {app_module} ---") |
| 19 | + print(f"--- Target Base URL: {BASE_URL} ---") |
| 20 | + |
| 21 | + # Set the app environment to development to avoid startup errors |
| 22 | + os.environ["APP_ENV"] = "development" |
| 23 | + |
| 24 | + try: |
| 25 | + module = importlib.import_module(app_module) |
| 26 | + app: FastAPI = getattr(module, app_attr) |
| 27 | + except Exception as e: |
| 28 | + print(f"Error: Could not import FastAPI app '{app_attr}' from module '{app_module}'.") |
| 29 | + print(f"Details: {e}") |
| 30 | + return |
| 31 | + |
| 32 | + ok_routes = [] |
| 33 | + error_routes = [] |
| 34 | + |
| 35 | + with httpx.Client(base_url=BASE_URL, follow_redirects=True) as client: |
| 36 | + for route in app.routes: |
| 37 | + # We can only automatically test GET routes that have no path parameters |
| 38 | + if "GET" in route.methods and "{" not in route.path: |
| 39 | + path = route.path |
| 40 | + print(f"Testing GET {path}...") |
| 41 | + try: |
| 42 | + # Some system endpoints require an admin API key |
| 43 | + headers = {"X-API-Key": "test_key"} |
| 44 | + response = client.get(path, headers=headers) |
| 45 | + if response.status_code == 200: |
| 46 | + ok_routes.append(path) |
| 47 | + else: |
| 48 | + error_routes.append(f"{path} (Status: {response.status_code})") |
| 49 | + except httpx.RequestError as e: |
| 50 | + error_routes.append(f"{path} (Request Error: {e})") |
| 51 | + |
| 52 | + print("\n--- API Audit Summary ---") |
| 53 | + if ok_routes: |
| 54 | + print("✅ OK Routes:") |
| 55 | + for r in sorted(ok_routes): |
| 56 | + print(f" - {r}") |
| 57 | + |
| 58 | + if error_routes: |
| 59 | + print("\n❌ Error Routes:") |
| 60 | + for r in sorted(error_routes): |
| 61 | + print(f" - {r}") |
| 62 | + |
| 63 | + if not error_routes: |
| 64 | + print("\nAll discoverable GET routes responded successfully.") |
| 65 | + |
| 66 | + |
| 67 | +if __name__ == "__main__": |
| 68 | + main() |
0 commit comments