drf-spectacular
drf-spectacular copied to clipboard
OAS 3.1.0 output: `maxLength` constraint not saved to schema for nullable string field
Describe the bug
We have several string fields in our API that are nullable (i.e., optional), but also have a max length. When using OAS 3.0.3 as the target schema version, this works fine, however with OAS 3.1.0, no maxLength
is stored. For non-nullable fields, maxLength
is stored properly.
I expect more constraints (e.g., minLength
should be obvious) are also dropped from the schema. Format specifiers (such as type: email
), readOnly
, writeOnly
and probably other specs work fine for nullable fields across OpenAPI versions, so there must be something special about constraint handling.
To Reproduce
Python code:
# Inside some model:
class Team(models.Model):
phone_number = models.CharField(null=True, blank=True, max_length=40)
Excerpt from generated OAS 3.0.3 schema:
TeamRequest:
type: object
properties:
phone_number:
type: string
nullable: true
maxLength: 40
Same excerpt from generated OAS 3.1.0 schema:
TeamRequest:
type: object
properties:
phone_number:
type:
- string
- 'null'
Expected behavior
Expected output should include maxLength
constraint.
If I understand the OpenAPI specs correctly (hints taken from this OpenAPI Spec question), this concise form should be fine:
TeamRequest:
type: object
description: Team info
properties:
phone_number:
type:
- string
- 'null'
maxLength: 40
If you want to be more explicit, this should work as well:
TeamRequest:
type: object
description: Team info
properties:
phone_number:
oneOf:
- type: string
maxLength: 40
- 'null'