Skip to content

Set body parameters to requestBody field in case if openapi 3 is used #131

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 50 additions & 6 deletions aiohttp_apispec/aiohttp_apispec.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,6 @@ def _register(self, app: web.Application):
def _register_route(
self, route: web.AbstractRoute, method: str, view: _AiohttpView
):

if not hasattr(view, "__apispec__"):
return None

Expand All @@ -197,11 +196,29 @@ def _update_paths(self, data: dict, method: str, url_path: str):
if method not in VALID_METHODS_OPENAPI_V2:
return None
for schema in data.pop("schemas", []):
parameters = self.plugin.converter.schema2parameters(
schema["schema"], location=schema["location"], **schema["options"]
)
self._add_examples(schema["schema"], parameters, schema["example"])
data["parameters"].extend(parameters)
if (
self.spec.components.openapi_version.major > 2
and self._is_body_location(schema["location"])
):
# in OpenAPI 3.0 in=body parameters must be put into requestBody
# https://apispec.readthedocs.io/en/latest/api_ext.html#apispec.ext.marshmallow.openapi.OpenAPIConverter.schema2parameters
# lets reinvent something that works, because apispec doesn't provide anything with which we could work
body = dict(**schema["options"])
body["schema"] = self.plugin.converter.resolve_nested_schema(
schema["schema"]
)
self._add_examples(schema["schema"], [body], schema["example"])
data["requestBody"] = {
"content": {
self._content_type(schema["location"]): body,
},
}
else:
parameters = self.plugin.converter.schema2parameters(
schema["schema"], location=schema["location"], **schema["options"]
)
self._add_examples(schema["schema"], parameters, schema["example"])
data["parameters"].extend(parameters)

existing = [p["name"] for p in data["parameters"] if p["in"] == "path"]
data["parameters"].extend(
Expand Down Expand Up @@ -264,6 +281,33 @@ def add_to_endpoint_or_ref():
else:
add_to_endpoint_or_ref()

def _content_type(self, location):
"""
extract body content type from parameters location

:param location: body location name, e.g. json, form etc
:return: return valid content-type header
"""
if not self._is_body_location(location):
raise ValueError(
f"Illegal location {location}, cannnot be converted to body"
)
if location == "json":
return "application/json"
if location == "form":
return "application/x-www-form-urlencoded"
# fallback to something generic
return "application/octet-stream"

def _is_body_location(self, location):
"""
check if location is valid body location

:param location: body location name, e.g. json, form etc
:return: True in case if location looks like body and False otherwises
"""
return location in ("files", "form", "json")


def setup_aiohttp_apispec(
app: web.Application,
Expand Down
2 changes: 1 addition & 1 deletion aiohttp_apispec/middlewares.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ async def validation_middleware(request: web.Request, handler) -> web.Response:
if isinstance(data, list):
result.extend(data)
else:
result=data
result = data
except (ValueError, TypeError):
result = data
break
Expand Down
13 changes: 8 additions & 5 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
setup_aiohttp_apispec,
validation_middleware,
)
from aiohttp_apispec.aiohttp_apispec import OpenApiVersion


class HeaderSchema(Schema):
Expand Down Expand Up @@ -79,14 +80,14 @@ def example_for_request_schema():
# since multiple locations are no longer supported
# in a single call, location should always expect string
params=[
({"location": "querystring"}, True),
({"location": "querystring"}, True),
({"location": "querystring"}, False),
({"location": "querystring"}, False),
({"location": "querystring"}, True, OpenApiVersion.V20),
({"location": "querystring"}, False, OpenApiVersion.V20),
({"location": "querystring"}, True, OpenApiVersion.V300),
({"location": "querystring"}, False, OpenApiVersion.V300),
]
)
def aiohttp_app(loop, aiohttp_client, request, example_for_request_schema):
location, nested = request.param
location, nested, openapi_version = request.param

@docs(
tags=["mytag"],
Expand Down Expand Up @@ -191,6 +192,7 @@ async def validated_view(request: web.Request):
url="/api/docs/api-docs",
swagger_path="/api/docs",
error_callback=my_error_handler,
openapi_version=openapi_version,
)
v1.router.add_routes(
[
Expand All @@ -216,6 +218,7 @@ async def validated_view(request: web.Request):
url="/v1/api/docs/api-docs",
swagger_path="/v1/api/docs",
error_callback=my_error_handler,
openapi_version=openapi_version,
)
app.router.add_routes(
[
Expand Down
Loading