diff --git a/CHANGELOG.rst b/CHANGELOG.rst index c47aded9..2c3b4e3d 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -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. diff --git a/src/apispec/ext/marshmallow/openapi.py b/src/apispec/ext/marshmallow/openapi.py index 3663fce6..a8553195 100644 --- a/src/apispec/ext/marshmallow/openapi.py +++ b/src/apispec/ext/marshmallow/openapi.py @@ -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, ): @@ -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, diff --git a/tests/test_ext_marshmallow_openapi.py b/tests/test_ext_marshmallow_openapi.py index 9d832002..0f1cfd47 100644 --- a/tests/test_ext_marshmallow_openapi.py +++ b/tests/test_ext_marshmallow_openapi.py @@ -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()