Merge pull request #2956 from markparonyan/api-issue-07-x7z6we

feat(api): generate unique readable OpenAPI operationIds
This commit is contained in:
Jeremy Grossmann 2026-10-08 19:26:08 +02:00 committed by GitHub
commit acfd4f9c1b
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
5 changed files with 149 additions and 0 deletions

View File

@ -0,0 +1,55 @@
#!/usr/bin/env python
#
# Copyright (C) 2026 GNS3 Technologies Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
Readable and unique OpenAPI operationIds.
"""
import re
from typing import Callable
from fastapi import APIRouter
from fastapi.routing import APIRoute
STUB_METHODS = ("GET", "POST", "DELETE", "PATCH", "PUT")
def _slug(value: str) -> str:
return re.sub(r"[^a-z0-9]+", "_", value.lower()).strip("_")
def generate_operation_id(route: APIRoute) -> str:
"""
Builds an operationId such as "nodes_get_node" from the first tag and the route name.
"""
name = _slug(route.name)
if route.tags:
tag = _slug(str(route.tags[0]))
if tag:
return f"{tag}_{name}"
return name
def add_stub_routes(router: APIRouter, endpoint: Callable, name: str) -> None:
"""
Registers a catch-all route per HTTP method so that every method gets its own operationId.
"""
for method in STUB_METHODS:
router.add_api_route("/{path:path}", endpoint, methods=[method], name=f"{name}_{method.lower()}")

View File

@ -21,6 +21,7 @@ from fastapi import Depends, FastAPI, Request
from fastapi.responses import JSONResponse
from starlette.exceptions import HTTPException as StarletteHTTPException
from gns3server.api.operation_ids import generate_operation_id
from gns3server.compute.compute_error import (
ComputeError,
ComputeForbiddenError,
@ -61,6 +62,7 @@ log = logging.getLogger(__name__)
compute_api = FastAPI(
title="GNS3 compute API",
description="This page describes the private compute API for GNS3. PLEASE DO NOT USE DIRECTLY!",
generate_unique_id_function=generate_operation_id,
version=__api_version__,
servers=[{"url": "/v3/compute"}],
)

View File

@ -18,6 +18,7 @@ from fastapi import APIRouter, Depends, HTTPException, status
# Check AI Copilot availability
from gns3server.agent import AI_COPILOT_AVAILABLE
from gns3server.api.operation_ids import add_stub_routes
from gns3server.config import Config
# Conditionally import AI-dependent routes
@ -44,6 +45,10 @@ else:
detail="AI Copilot is not available. Install AI dependencies with: pip install gns3-server[ai-features]",
)
add_stub_routes(_chat_router, ai_not_available, "chat_not_available")
add_stub_routes(_copilot_router, ai_not_available, "copilot_not_available")
add_stub_routes(_llm_router, ai_not_available, "llm_not_available")
from . import (
acl,

View File

@ -37,6 +37,7 @@ from uvicorn.main import Server as UvicornServer
# MCP is an optional feature — import only if dependencies are installed
from gns3server.agent import MCP_AVAILABLE
from gns3server.api.errors import customize_openapi_errors, error_response
from gns3server.api.operation_ids import add_stub_routes, generate_operation_id
from gns3server.api.routes import controller, index
from gns3server.api.routes.compute import compute_api
from gns3server.config import Config
@ -68,6 +69,8 @@ else:
detail="MCP is not available. Install AI dependencies with: pip install gns3-server[ai-features]",
)
add_stub_routes(_mcp_router, mcp_not_available, "not_available")
import logging
@ -91,6 +94,7 @@ def get_application() -> FastAPI:
servers=[{"url": "/"}],
docs_url=None,
redoc_url=None,
generate_unique_id_function=generate_operation_id,
)
application.add_middleware(

View File

@ -0,0 +1,83 @@
#!/usr/bin/env python
#
# Copyright (C) 2026 GNS3 Technologies Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import re
import warnings
from collections import Counter
import pytest
from fastapi import APIRouter, FastAPI
from fastapi.openapi.utils import get_openapi
from gns3server.api.operation_ids import STUB_METHODS, add_stub_routes, generate_operation_id
from gns3server.api.routes.compute import compute_api
from gns3server.api.server import app as controller_app
HTTP_METHODS = ("get", "put", "post", "delete", "options", "head", "patch", "trace")
def build_operation_ids(application: FastAPI) -> list[str]:
with warnings.catch_warnings():
warnings.simplefilter("error")
spec = get_openapi(title="test", version="0", routes=application.routes)
return [
operation["operationId"]
for path_item in spec["paths"].values()
for method, operation in path_item.items()
if method in HTTP_METHODS
]
@pytest.mark.parametrize("application", [controller_app, compute_api], ids=["controller", "compute"])
def test_operation_ids_are_unique_and_readable(application: FastAPI) -> None:
operation_ids = build_operation_ids(application)
assert operation_ids
duplicates = [operation_id for operation_id, count in Counter(operation_ids).items() if count > 1]
assert duplicates == []
invalid = [operation_id for operation_id in operation_ids if not re.fullmatch(r"[a-z0-9_]+", operation_id)]
assert invalid == []
def test_operation_id_uses_first_tag_and_function_name() -> None:
router = APIRouter()
@router.get("/nodes/{node_id}", tags=["Compute nodes", "Other"])
async def get_node(node_id: str):
return {}
@router.get("/untagged")
async def list_untagged():
return {}
assert generate_operation_id(router.routes[0]) == "compute_nodes_get_node"
assert generate_operation_id(router.routes[1]) == "list_untagged"
def test_stub_routes_get_one_operation_id_per_method() -> None:
async def not_available(path: str = ""):
return {}
application = FastAPI(generate_unique_id_function=generate_operation_id)
router = APIRouter(tags=["Stub"])
add_stub_routes(router, not_available, "stub")
application.include_router(router, prefix="/stub")
assert sorted(build_operation_ids(application)) == sorted(f"stub_stub_{method.lower()}" for method in STUB_METHODS)