Skip to content

OpenAPI schema contains invalid unicode characters if project uses a Django URL field #175

@fyhertz

Description

@fyhertz

Describe the bug

Not really a bug of drf-spectacular per se, but probably worth mentioning:

When using django.db.model.URLField, the OpenAPI spec ends up containing the same regex pattern that Django uses to validates URLs:

"url": {
  "type": "string",
  "format": "uri",
  "nullable": true,
  "maxLength": 200,
  "pattern": "^(?:[a-z0-9.+-]*)://(?:[^\\s:@/]+(?::[^\\s:@/]*)?@)?(?:(?:25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}|\\[[0-9a-f:.]+\\]|([a-z¡-�0-9](?:[a-z¡-�0-9-]{0,61}[a-z¡-�0-9])?(?:\\.(?!-)[a-z¡-�0-9-]{1,63}(?<!-))*\\.(?!-)(?:[a-z¡-�-]{2,63}|xn--[a-z0-9]{1,59})(?<!-)\\.?|localhost))(?::\\d{2,5})?(?:[/?#][^\\s]*)?\\Z"
}

Issues arise when the JSON or YAML parser used by a consumer of OpenAPI specs does not allow such characters. For instance pyyaml will raise an error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/simon/work/venv/lib/python3.8/site-packages/yaml/__init__.py", line 162, in safe_load
    return load(stream, SafeLoader)
  File "/home/simon/work/venv/lib/python3.8/site-packages/yaml/__init__.py", line 112, in load
    loader = Loader(stream)
  File "/home/simon/work/venv/lib/python3.8/site-packages/yaml/loader.py", line 34, in __init__
    Reader.__init__(self, stream)
  File "/home/simon/work/venv/lib/python3.8/site-packages/yaml/reader.py", line 74, in __init__
    self.check_printable(stream)
  File "/home/simon/work/venv/lib/python3.8/site-packages/yaml/reader.py", line 143, in check_printable
    raise ReaderError(self.name, position, ord(character),
yaml.reader.ReaderError: unacceptable character #xffff: special characters are not allowed
  in "<unicode string>", position 101019

Expected behavior

What do you think is the best approach here? Should OpenAPI specs produced by drf-spectacular avoid invalid unicode characters?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions