Skip to content
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

Cannot generate top level array schemas #92

Open
yeralin opened this issue Sep 30, 2019 · 1 comment
Open

Cannot generate top level array schemas #92

yeralin opened this issue Sep 30, 2019 · 1 comment

Comments

@yeralin
Copy link
Contributor

yeralin commented Sep 30, 2019

Consider following schema:

from marshmallow import Schema, fields

class UserSchema(Schema):
    username = fields.String()
    age = fields.Integer()

Now, say my payload is of this form:

[{"username": "test-1", "age": 1}, {"username": "test-2", "age": 2}]

The JSON Schema that could describe this payload could be:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "array", <- important part
  "definitions": {
      "UserSchema": {
        "items": {
            "properties": {
              "username": {
                "type": "string",
                "title": "username"
              },
              "age": {
                "type": "number",
                "format": "integer"
                "title": "age"
              }
            }
          }
      }
  }
}

So, in theory to generate this schema using marshmallow-jsonschema we could do the following:

user_schema = UserSchema(many=True)
JSONSchema().dump(user_schema).data

However, that's not the case. The resulting schema would be:

{
    "$schema": "http://json-schema.org/draft-07/schema#",
    "$ref": "#/definitions/UserSchema",
    "definitions": {
        "UserSchema": {
            "properties": {
                "age": {
                    "title": "age",
                    "type": "number",
                    "format": "integer"
                },
                "username": {
                    "title": "username",
                    "type": "string"
                }
            },
            "type": "object", <- notice, type is always "object"
            "additionalProperties": false
        }
    }
}

Setting many=True during schema instantiation does not affect the resulting JSON schema. According to

type = fields.Constant("object")

It will always be set to "type": "object" irregardless of many option.

@lindycoder
Copy link

lindycoder commented Jul 26, 2021

This quick fix seems to work for me:

    schema = JSONSchema().dump(MySchema(many=True))  # Note that the many=true is ignored
    schema.update(
        type='array',
        items={
            'type': 'object',
            '$ref': schema.pop('$ref'),
        },
    )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants