Skip to content
Closed
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
6 changes: 6 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@ Changelog
unreleased
**********

Bug fixes:

- ``schema2parameters``: Default parameter ``name`` to schema class name or
``"body"`` if not specified (:issue:`829`).
Thanks :user:`rd3x` for reporting.

Other changes:

- Drop support for marshmallow 3, which is EOL.
Expand Down
13 changes: 11 additions & 2 deletions src/apispec/ext/marshmallow/openapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,8 +139,8 @@ def schema2parameters(
self,
schema,
*,
location,
name: str = "body",
location: str,
name: str | None = None,
required: bool = False,
description: str | None = None,
):
Expand All @@ -157,6 +157,15 @@ def schema2parameters(
location = __location_map__.get(location, location)
# OAS 2 body parameter
if location == "body":
if name is None:
if isinstance(schema, marshmallow.Schema):
name = schema.__class__.__name__
elif isinstance(schema, type) and issubclass(
schema, marshmallow.Schema
):
name = schema.__name__
else:
name = "body"
param = {
"in": location,
"required": required,
Expand Down
22 changes: 22 additions & 0 deletions tests/test_ext_marshmallow_openapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -363,6 +363,28 @@ class UserSchema(Schema):
assert param["schema"]["type"] == "array"
assert param["schema"]["items"] == {"$ref": "#/definitions/User"}

# json/body is invalid for OpenAPI 3
@pytest.mark.parametrize("openapi", ("2.0",), indirect=True)
def test_schema_body_name_default(self, openapi):
class UserSchema(Schema):
name = fields.Str()

# Schema class defaults to class name
res = openapi.schema2parameters(UserSchema, location="body")
assert res[0]["name"] == "UserSchema"

# Schema instance defaults to class name
res = openapi.schema2parameters(UserSchema(), location="body")
assert res[0]["name"] == "UserSchema"

# Explicit name overrides default
res = openapi.schema2parameters(UserSchema, location="body", name="custom_name")
assert res[0]["name"] == "custom_name"

# Non-schema fallback defaults to "body"
res = openapi.schema2parameters("UserRef", location="body")
assert res[0]["name"] == "body"

def test_schema_query(self, openapi):
class UserSchema(Schema):
name = fields.Str()
Expand Down