Schemas updated

This commit is contained in:
2025-04-02 18:53:33 +03:00
parent 27c48bb86a
commit 3583d178e9
38 changed files with 2672 additions and 28 deletions

View File

@@ -1,15 +1,16 @@
import uvicorn
from ApiServices.TemplateService.config import template_api_config
from config import api_config
from ApiServices.TemplateService.create_app import create_app
# from prometheus_fastapi_instrumentator import Instrumentator
app = create_app() # Create FastAPI application
# Instrumentator().instrument(app=app).expose(app=app) # Setup Prometheus metrics
app = create_app() # Create FastAPI application
# Instrumentator().instrument(app=app).expose(app=app) # Setup Prometheus metrics
if __name__ == "__main__":
# Run the application with Uvicorn Server
uvicorn_config = uvicorn.Config(**template_api_config.app_as_dict)
uvicorn_config = uvicorn.Config(**api_config.app_as_dict)
uvicorn.Server(uvicorn_config).run()

View File

@@ -61,4 +61,4 @@ class Configs(BaseSettings):
model_config = SettingsConfigDict(env_prefix="API_")
template_api_config = Configs()
api_config = Configs()

View File

@@ -1,8 +1,9 @@
from fastapi import APIRouter
from .test_template.route import test_template_route
def get_routes() -> list[APIRouter]:
return []
return [test_template_route]
def get_safe_endpoint_urls() -> list[tuple[str, str]]:
@@ -14,4 +15,6 @@ def get_safe_endpoint_urls() -> list[tuple[str, str]]:
("/auth/register", "POST"),
("/auth/login", "POST"),
("/metrics", "GET"),
("/test/template", "GET"),
("/test/template", "POST"),
]

View File

@@ -0,0 +1,40 @@
from fastapi import APIRouter, Request, Response
test_template_route = APIRouter(prefix="/test", tags=["Test"])
@test_template_route.get(path="/template", description="Test Template Route")
def test_template(request: Request, response: Response):
"""
Test Template Route
"""
headers = dict(request.headers)
response.headers["X-Header"] = "Test Header GET"
return {
"completed": True,
"message": "Test Template Route",
"info": {
"host": headers.get("host", "Not Found"),
"user_agent": headers.get("user-agent", "Not Found"),
},
}
@test_template_route.post(
path="/template",
description="Test Template Route with Post Method",
)
def test_template_post(request: Request, response: Response):
"""
Test Template Route with Post Method
"""
headers = dict(request.headers)
response.headers["X-Header"] = "Test Header POST"
return {
"completed": True,
"message": "Test Template Route with Post Method",
"info": {
"host": headers.get("host", "Not Found"),
"user_agent": headers.get("user-agent", "Not Found"),
},
}

View File

@@ -1,12 +1,8 @@
from fastapi import Request, Response
def get_safe_endpoint_urls() -> list:
return []
from ApiServices.TemplateService.endpoints.routes import get_safe_endpoint_urls
async def token_middleware(request: Request, call_next):
# from application.routes.routes import get_safe_endpoint_urls
base_url = "/".join(request.url.path.split("/")[:3])
safe_endpoints = [_[0] for _ in get_safe_endpoint_urls()]

View File

@@ -2,7 +2,9 @@ from typing import Any, Dict
from fastapi import FastAPI
from fastapi.routing import APIRoute
from fastapi.openapi.utils import get_openapi
from ApiServices.TemplateService.config import template_api_config
from ApiServices.TemplateService.endpoints.routes import get_safe_endpoint_urls
class OpenAPISchemaCreator:
@@ -18,8 +20,11 @@ class OpenAPISchemaCreator:
app: FastAPI application instance
"""
self.app = app
self.safe_endpoint_list: list[tuple[str, str]] = get_safe_endpoint_urls()
self.routers_list = self.app.routes
def create_security_schemes(self) -> Dict[str, Any]:
@staticmethod
def create_security_schemes() -> Dict[str, Any]:
"""
Create security scheme definitions.
@@ -36,6 +41,30 @@ class OpenAPISchemaCreator:
}
}
def configure_route_security(
self, path: str, method: str, schema: Dict[str, Any]
) -> None:
"""
Configure security requirements for a specific route.
Args:
path: Route path
method: HTTP method
schema: OpenAPI schema to modify
"""
if not schema.get("paths", {}).get(path, {}).get(method):
return
# Check if endpoint is in safe list
endpoint_path = f"{path}:{method}"
list_of_safe_endpoints = [
f"{e[0]}:{str(e[1]).lower()}" for e in self.safe_endpoint_list
]
if endpoint_path not in list_of_safe_endpoints:
if "security" not in schema["paths"][path][method]:
schema["paths"][path][method]["security"] = []
schema["paths"][path][method]["security"].append({"BearerAuth": []})
def create_schema(self) -> Dict[str, Any]:
"""
Create the complete OpenAPI schema.
@@ -46,7 +75,7 @@ class OpenAPISchemaCreator:
openapi_schema = get_openapi(
title=template_api_config.TITLE,
description=template_api_config.DESCRIPTION,
version=template_api_config,
version=template_api_config.VERSION,
routes=self.app.routes,
)
@@ -56,7 +85,7 @@ class OpenAPISchemaCreator:
openapi_schema["components"][
"securitySchemes"
] = self._create_security_schemes()
] = self.create_security_schemes()
# Configure route security and responses
for route in self.app.routes: