drf-standardized-errors icon indicating copy to clipboard operation
drf-standardized-errors copied to clipboard

Use Pattern type rather than Enum type for error component attr property

Open GiancarloFusiello opened this issue 1 year ago • 2 comments

As described here in issue #74 , for DRF serializer ListField or DictField drf-spectacular combined with drf-standardized-errors will generate the following:

list_field_nameINDEXErrorComponent:
      type: object
      properties:
        attr:
          enum:
          - list_field_name.INDEX
          type: string
          description: '* `list_field_name.INDEX` - list_field_name.INDEX'
        code:
          enum:
          - blank
          - invalid
          - max_length
          - 'null'
          - null_characters_not_allowed
          - required
          - surrogate_characters_not_allowed
          type: string
          description: |-
            * `blank` - blank
            * `invalid` - invalid
            * `max_length` - max_length
            * `null` - null
            * `null_characters_not_allowed` - null_characters_not_allowed
            * `required` - required
            * `surrogate_characters_not_allowed` - surrogate_characters_not_allowed
        detail:
          type: string

If you're like me and use Schemathesis to generate and run tests against your documented API, this will result in errors due to list_field_name.INDEX being a string literal as see here:

- Response violates schema

    'null' is not one of ['parse_error']

    Schema:

        {
            "enum": [
                "parse_error"
            ],
            "type": "string",
            "description": "* `parse_error` - Parse Error"
        }

    Value:

        "null"

[400] Bad Request:

    `{"type":"validation_error","errors":[{"code":"null","detail":"This field may not be null.","attr":"list_field_name.0"}]}`

Reproduce with:

    curl -X POST -H 'Authorization: [Filtered]' -H 'Content-Type: application/json' -H 'Cookie: [Filtered]' -d '{"list_field_name": [null]}' http://0.0.0.0:8000/api/my-resource/

Suggestion To use the Pattern data type rather than Enum for the attr error component property. Examples can be found here.

GiancarloFusiello avatar Jun 20 '24 16:06 GiancarloFusiello