Skip to content

Commit

Permalink
Refactor API router and add custom OpenAPI configuration
Browse files Browse the repository at this point in the history
  • Loading branch information
fvergaracl committed Mar 7, 2024
1 parent 7b7fb92 commit 5b54cf8
Show file tree
Hide file tree
Showing 5 changed files with 82 additions and 10 deletions.
6 changes: 3 additions & 3 deletions app/api/v1/endpoints/strategy.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

router = APIRouter(
prefix="/strategies",
tags=["Strategies"],
tags=["strategies"],
)


Expand All @@ -26,7 +26,7 @@ def get_strategy_list(
return service.get_list(schema)


@router.get("/{id}", response_model=FindStrategyResult)
@router.get("{id}", response_model=FindStrategyResult)
@inject
def get_strategy_by_id(
id: str,
Expand All @@ -47,7 +47,7 @@ def create_strategy(
return service.create_strategy(schema)


@router.get("/rules/variable", response_model=ResponseFindAllRuleVariables)
@router.get("rules/variable", response_model=ResponseFindAllRuleVariables)
@inject
def get_variables_available_to_strategy(
service: RulesService = Depends(Provide[Container.rules_service]),
Expand Down
62 changes: 57 additions & 5 deletions app/main.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,68 @@
from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware

import subprocess
import toml
from app.api.v1.routes import routers as v1_routers
from app.core.config import configs
from app.core.container import Container
from app.util.class_object import singleton
from fastapi.openapi.utils import get_openapi
from app.schema.base_schema import RootEndpoint


def get_project_data():
# Asegúrate de que la ruta sea accesible desde tu script
pyproject_path = "pyproject.toml"
with open(pyproject_path, "r") as pyproject_file:
pyproject_content = toml.load(pyproject_file)
return pyproject_content['tool']['poetry']


project_data = get_project_data()


def custom_openapi():
if app.openapi_schema:
return app.openapi_schema
openapi_schema = get_openapi(
title=project_data['name'],
version=project_data['version'],
description=project_data['description'],
routes=app.routes,
servers=[{"url": "/api/v1", "description": "Local"}]
)
# Eliminar el prefijo /api/v1 de las rutas en la documentación de Swagger
for path in list(openapi_schema["paths"].keys()):
if path.startswith("/api/v1"):
openapi_schema["paths"][path[7:]
] = openapi_schema["paths"].pop(path)
app.openapi_schema = openapi_schema
return app.openapi_schema


def get_git_commit_hash() -> str:
"""
Returns the current git commit hash, or "unknown" if not available.
"""
try:

commit_hash = subprocess.check_output(
["git", "rev-parse", "HEAD"]).decode("ascii").strip()
except Exception:
commit_hash = "unknown"
return commit_hash


@singleton
class AppCreator:
def __init__(self):
# set app default
self.app = FastAPI(
title=configs.PROJECT_NAME,
openapi_url=f"{configs.API}/openapi.json",
version="0.0.1",
redoc_url="/redocs",
docs_url="/docs",
servers=[{"url": configs.API_V1_STR, "description": "Local"}]
)
self.app.openapi = custom_openapi

# set db and container
self.container = Container()
Expand All @@ -36,7 +81,13 @@ def __init__(self):
)

# set routes
@self.app.get("")
@self.app.get(
"/api/v1",
tags=["root"],
response_model=RootEndpoint,
summary="Root API v1 endpoint",
description="General information about the API"
)
def root():
version = configs.GAMIFICATIONENGINE_VERSION_APP
project_name = configs.PROJECT_NAME
Expand All @@ -46,6 +97,7 @@ def root():
"message": "Welcome to GAME API",
"docs": "/docs",
"redocs": "/redocs",
"commitVersion": get_git_commit_hash()
}

# set routers API_V1_STR
Expand Down
9 changes: 9 additions & 0 deletions app/schema/base_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,15 @@
from pydantic import BaseModel


class RootEndpoint(BaseModel):
projectName: str
version: str
message: str
docs: str
redocs: str
commitVersion: str


class ModelBaseInfo(BaseModel):
id: UUID
created_at: datetime
Expand Down
14 changes: 12 additions & 2 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ watchgod = "0.8.2"
websockets = "12.0"
zipp = "3.17.0"
vulture = "^2.11"
toml = "^0.10.2"


[build-system]
Expand Down

0 comments on commit 5b54cf8

Please sign in to comment.