Skip to content

refactor(api): split the API routes into one router per resource - #142

Merged
Goldokpa merged 3 commits into
Climate-Vision:mainfrom
Ayomipo18:refactor/issue-58-modular-api-routers
Nov 25, 2026
Merged

Goldokpa merged 3 commits into
Climate-Vision:mainfrom
Ayomipo18:refactor/issue-58-modular-api-routers

Conversation

@Ayomipo18

@Ayomipo18 Ayomipo18 commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Splits src/climatevision/api/main.py into one APIRouter per resource, as proposed in #58. All routes were defined inline in create_app(), and the file had grown to 1553 lines since the issue was filed. main.py is now 172 lines: it builds the app, adds the middleware and includes the routers.

The code is moved, not changed. The OpenAPI schema, the route table (paths, methods, names, order) and the middleware stack are byte-for-byte identical before and after, both with and without a built frontend.

Related Issue

Closes #58

Type of Change

  • Bug fix
  • New feature
  • Breaking change
  • Documentation update
  • Refactor / code cleanup
  • CI / build / tooling change

Key Changes

src/climatevision/api/
├── main.py              # create_app(): middleware, admin router, include_routers(), frontend
├── shared.py            # types and helpers used by more than one router
└── routes/
    ├── __init__.py      # ROUTERS + include_routers(app)
    ├── health.py        # /api/health, /api/health/models
    ├── analysis.py      # /api/analysis-types
    ├── runs.py          # /api/runs, /ws/runs/{run_id}, /api/reports/{run_id}
    ├── predict.py       # /api/predict, /api/predict/upload
    ├── explain.py       # /api/explain
    ├── organizations.py # /api/organizations
    ├── subscriptions.py # /api/organizations/{id}/subscriptions
    └── alerts.py        # /api/organizations/{id}/alerts, /api/alerts/{id}/...
  • Each request/response model moved with the router that uses it. The existing schemas.py is left alone: nothing imports it, and its AnalysisType lacks flooding_sar, so switching to it would change validation.
  • The routers are included in the order the routes were defined, so matching order is unchanged. The admin router and the / redirect stay ahead of them, and the frontend fallback stays last.
  • PROJECT_ROOT in shared.py replaces the three Path(__file__).resolve().parents[3] lookups. Copied into routes/, they would have resolved one directory too high, so the uploads, the template result and the model weights check would have looked in the wrong place.
  • The moved code keeps its names, including the _-prefixed helpers, so it can be matched line for line with git diff --color-moved --color-moved-ws=allow-indentation-change. Apart from the indentation and @app. → @router., the only differences are black's formatting of the new files.
  • explain_prediction was imported in main.py but never used, so it was not carried over.

Testing

  • Unit tests pass locally (pytest tests/): 235 passed, 1 skipped, on both Python 3.9 / FastAPI 0.128 and Python 3.11 / FastAPI 0.165. The one failure, test_onnx_inference.py::test_run_inference_reports_backend_and_latency, fails the same way on main locally (missing ONNX runtime).
  • Manual API test (curl / OpenAPI docs): compared app.openapi(), the middleware stack and the responses to a set of GET requests (API paths, unknown paths, deep links) before and after, with and without frontend/dist. They are identical with FastAPI 0.128 (Python 3.9) and with 0.165 (Python 3.11, what CI installs). On 0.128 the route table (app.routes, including order) is identical too.
  • Frontend smoke test (npm run dev): no frontend change. npm run build passes.
  • New tests added for this change

Tests that patched climatevision.api.main.run_inference_from_gee now patch climatevision.api.routes.predict.run_inference_from_gee, where the code now looks it up. WS_RUN_NOT_FOUND is imported from routes.runs.

The new tests/test_api_routers.py checks that:

  • every router's routes are in the app's OpenAPI schema. It fails if a router is dropped from ROUTERS, which I checked.
  • no path and method is defined by two routers.
  • with a built frontend, an API path still reaches the API and a deep link like /runs gets index.html. It builds the app over a temporary frontend/dist and fails if the routers are included after the fallback, which I checked.
  • PROJECT_ROOT is the repository root.

The first version of these tests compared app.routes with the routers' routes and failed in CI. FastAPI 0.165 keeps an included router as a single entry in app.routes, so the second commit checks behaviour instead of that internal list.

flake8 src/ --select=E9,F63,F7,F82 reports 0, and the new files are black-clean.

Found along the way, not changed here: GET /api/runs/stats returns a 500 on main with any database. It counts acknowledged = 0 in the alerts table, but only organization_alerts has that column. This PR moves the code as it is, so I'll open a separate issue and fix for it.

Open PRs: #141 merges cleanly on top of this branch, and its tests pass after the merge. The older open PRs that edit main.py (#27, #28, #31, #56) would need to move their changes into the matching router.

Checklist

All routes of the API were defined inline in create_app() in api/main.py,
which had grown to 1553 lines. Each resource now has its own APIRouter in
api/routes/ (health, analysis, runs, predict, explain, organizations,
subscriptions, alerts), and main.py only builds the app, adds middleware
and includes the routers.

Types and helpers used by more than one router move to api/shared.py, with
a PROJECT_ROOT constant replacing the parents[3] lookups, which would have
resolved to the wrong directory one level deeper in routes/.

The code is moved, not changed: the OpenAPI schema, the route table and
the middleware stack are identical before and after, with and without a
built frontend. Tests that patched climatevision.api.main now patch the
module the code moved to, and a new test checks that every router is
included, that no route is defined twice, that API routes are matched
before the frontend fallback, and where PROJECT_ROOT points.

Closes Climate-Vision#58
@Ayomipo18
Ayomipo18 requested a review from Goldokpa as a code owner November 24, 2026 18:07
FastAPI 0.165, which CI installs, keeps an included router as a single
entry in app.routes instead of copying its routes there, so comparing
app.routes with the routers' routes failed in CI although every route
is served. The wiring is now checked against the paths of the OpenAPI
schema, and the order against the frontend fallback with requests to an
app built over a temporary frontend/dist.
Brings in Climate-Vision#144. Its fix to get_run_stats, which now counts alerts from
organization_alerts, is applied in routes/runs.py, where the endpoint
moved to; main.py keeps the refactored version.
@Goldokpa

Copy link
Copy Markdown
Member

Thanks @Ayomipo18, this has been needed for a while: main.py was past 1500 lines. Checking the OpenAPI schema, the route table and real requests before and after, with and without a built frontend, is what makes a move this size safe to merge. PROJECT_ROOT catching the parents[3] paths before they broke was a nice touch too. I've merged #144 first, and the stats fix carried into routes/runs.py cleanly, with CI green. Merging.

@Goldokpa
Goldokpa merged commit b27fc2a into Climate-Vision:main Nov 25, 2026
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Refactor API into modular routers

2 participants