Skip to content

Commit

Permalink
feat: openapi config override (#1002)
Browse files Browse the repository at this point in the history
* feat(openapi): override openapi json

* add docs

* fix(ci):

* rename: openapi_json_path => openapi_file_path

---------

Co-authored-by: Sanskar Jethi <[email protected]>
  • Loading branch information
VishnuSanal and sansyrox authored Nov 2, 2024
1 parent deea29a commit 9924437
Show file tree
Hide file tree
Showing 6 changed files with 129 additions and 1 deletion.
4 changes: 4 additions & 0 deletions docs_src/src/pages/documentation/api_reference/openapi.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ Out of the box, the following endpoints are setup for you:
- `/docs` The Swagger UI
- `/openapi.json` The JSON Specification

To use a custom openapi configuration, you can:

- Place the `openapi.json` config file in the root directory.
- Or, pass the file path to the `openapi_file_path` parameter in the `Robyn()` constructor. (the parameter gets priority over the file).

However, if you don't want to generate the OpenAPI docs, you can disable it by passing `--disable-openapi` flag while starting the application.

Expand Down
5 changes: 5 additions & 0 deletions docs_src/src/pages/documentation/example_app/openapi.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@ Out of the box, the following endpoints are setup for you:

However, if you don't want to generate the OpenAPI docs, you can disable it by passing `--disable-openapi` flag while starting the application.

To use a custom openapi configuration, you can:

- Place the `openapi.json` config file in the root directory.
- Or, pass the file path to the `openapi_file_path` parameter in the `Robyn()` constructor. (the parameter gets priority over the file).

```bash
python app.py --disable-openapi
```
Expand Down
69 changes: 69 additions & 0 deletions integration_tests/openapi_config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
{
"openapi": "3.1.0",
"info": {
"title": "Robyn Test API",
"version": "1.0.0",
"description": null,
"termsOfService": null,
"contact": {
"name": null,
"url": null,
"email": null
},
"license": {
"name": null,
"url": null
},
"servers": [],
"externalDocs": {
"description": null,
"url": null
},
"components": {
"schemas": {},
"responses": {},
"parameters": {},
"examples": {},
"requestBodies": {},
"securitySchemes": {},
"links": {},
"callbacks": {},
"pathItems": {}
}
},
"paths": {
"/": {
"get": {
"summary": "",
"description": "No description provided",
"parameters": [],
"tags": [
"get"
],
"responses": {
"200": {
"description": "Successful Response",
"content": {
"text/plain": {
"schema": {}
}
}
}
}
}
}
},
"components": {
"schemas": {},
"responses": {},
"parameters": {},
"examples": {},
"requestBodies": {},
"securitySchemes": {},
"links": {},
"callbacks": {},
"pathItems": {}
},
"servers": [],
"externalDocs": null
}
20 changes: 20 additions & 0 deletions integration_tests/test_openapi.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,26 @@
import pytest

from integration_tests.helpers.http_methods_helpers import get
from robyn import Robyn


@pytest.mark.benchmark
def test_custom_openapi_spec():
app = Robyn(__file__, openapi_file_path="openapi_config.json")

openapi_spec = app.openapi.openapi_spec

assert isinstance(openapi_spec, dict)

assert "openapi" in openapi_spec
assert "info" in openapi_spec
assert "paths" in openapi_spec
assert "components" in openapi_spec
assert "servers" in openapi_spec
assert "externalDocs" in openapi_spec

assert openapi_spec["info"]["title"] == "Robyn Test API"
assert openapi_spec["info"]["version"] == "1.0.0"


@pytest.mark.benchmark
Expand Down
9 changes: 8 additions & 1 deletion robyn/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import logging
import os
import socket
from pathlib import Path
from typing import Callable, List, Optional, Tuple, Union

import multiprocess as mp
Expand Down Expand Up @@ -41,6 +42,7 @@ def __init__(
self,
file_object: str,
config: Config = Config(),
openapi_file_path: str = None,
openapi: OpenAPI = OpenAPI(),
dependencies: DependencyMap = DependencyMap(),
) -> None:
Expand All @@ -51,6 +53,11 @@ def __init__(
self.dependencies = dependencies
self.openapi = openapi

if openapi_file_path:
openapi.override_openapi(Path(self.directory_path).joinpath(openapi_file_path))
elif Path(self.directory_path).joinpath("openapi.json").exists():
openapi.override_openapi(Path(self.directory_path).joinpath("openapi.json"))

if not bool(os.environ.get("ROBYN_CLI", False)):
# the env variables are already set when are running through the cli
load_vars(project_root=directory_path)
Expand Down Expand Up @@ -583,7 +590,7 @@ def configure_authentication(self, authentication_handler: AuthenticationHandler

class SubRouter(Robyn):
def __init__(self, file_object: str, prefix: str = "", config: Config = Config(), openapi: OpenAPI = OpenAPI()) -> None:
super().__init__(file_object, config, openapi)
super().__init__(file_object=file_object, config=config, openapi=openapi)
self.prefix = prefix

def __add_prefix(self, endpoint: str):
Expand Down
23 changes: 23 additions & 0 deletions robyn/openapi.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import inspect
import json
import typing
from dataclasses import asdict, dataclass, field
from importlib import resources
from inspect import Signature
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, TypedDict

from robyn.responses import FileResponse, html
Expand Down Expand Up @@ -138,11 +140,15 @@ class OpenAPI:

info: OpenAPIInfo = field(default_factory=OpenAPIInfo)
openapi_spec: dict = field(init=False)
openapi_file_override: bool = False # denotes whether there is an override or not.

def __post_init__(self):
"""
Initializes the openapi_spec dict
"""
if self.openapi_file_override:
return

self.openapi_spec = {
"openapi": "3.1.0",
"info": asdict(self.info),
Expand All @@ -163,6 +169,9 @@ def add_openapi_path_obj(self, route_type: str, endpoint: str, openapi_name: str
@param handler: Callable the handler function for the endpoint
"""

if self.openapi_file_override:
return

query_params = None
request_body = None
return_annotation = None
Expand Down Expand Up @@ -212,6 +221,10 @@ def add_subrouter_paths(self, subrouter_openapi: "OpenAPI"):
@param subrouter_openapi: OpenAPI the OpenAPI object of the current subrouter
"""

if self.openapi_file_override:
return

paths = subrouter_openapi.openapi_spec["paths"]

for path in paths:
Expand Down Expand Up @@ -393,6 +406,16 @@ def get_schema_object(self, parameter: str, param_type: Any) -> dict:

return properties

def override_openapi(self, openapi_json_spec_path: Path):
"""
Set a pre-configured OpenAPI spec
@param openapi_json_spec_path: str the path to the json file
"""
with open(openapi_json_spec_path) as json_file:
json_file_content = json.load(json_file)
self.openapi_spec = dict(json_file_content)
self.openapi_file_override = True

def get_openapi_docs_page(self) -> FileResponse:
"""
Handler to the swagger html page to be deployed to the endpoint `/docs`
Expand Down

0 comments on commit 9924437

Please sign in to comment.