marshmallow-code / marshmallow-code/apispec

Multiple schemas for same nested type in data class with marshmallow-dataclass > 8.5.3

Open
#762 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
1.2k
Forks
202
Avg merge
3h 38m
Merged PRs (30d)
3

Description

When generating a schema for a single data class referencing same nested type in multiple fields each field get a separate schema. Even though it is the same type. Though, the trick is that this only happens if you first get the schema for the type in a different call context.

Code to reproduce the bug:

```
from dataclasses import dataclass

import marshmallow_dataclass
from apispec import APISpec
from apispec.ext.marshmallow import MarshmallowPlugin

@dataclass
class Foo:
s: str

@dataclass
class Bar:
a: Foo
b: Foo

def get_marshmallow_schema():
marshmallow_dataclass.class_schema(Bar)()

# When this function is called the bug is triggered. Commenting out this line makes the bug not happen.
get_marshmallow_schema()

spec = APISpec(
title="Test schema",
version="0.0.1",
openapi_version="3.0.3",
plugins=[MarshmallowPlugin()],
)

spec.components.schema("bar", schema=marshmallow_dataclass.class_schema(Bar))

print(spec.to_yaml())
```
Running the above code will output the warning from marshmallow plugin:
_UserWarning: Multiple schemas resolved to the name Foo. The name has been modified. Either manually add each of the schemas with a different name or provide a custom schema_name_resolver._

And the schema for Bar will look like:
```
properties:
a:
$ref: '#/components/schemas/Foo1'
b:
$ref: '#/components/schemas/Foo'
required:
- a
- b
type: object
```

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by running the provided reproduction with marshmallow_dataclass.class_schema(Bar), get_marshmallow_schema(), APISpec, and MarshmallowPlugin. Trace how spec.components.schema("bar", ...) resolves the two Foo fields after the earlier schema call. Done means the warning is gone and both Bar fields reference the same Foo schema.

Written by the indexing model from the issue text.

Assessment

Tech stack
openapi, python
Domain
api
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
58/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.