Skip to content

Schema-derived string/enum example is emitted unencoded as an application/json body, failing the http lexer #172

Open

Description

@dstrodtman

With :examples:, a response whose schema is a bare type: string (for example an enum) produces an example body that isn't valid JSON, even though the block is emitted under Content-Type: application/json. Pygments then fails to lex it and Sphinx warns. Under sphinx-build -W that's fatal.

Minimal reproducer

spec.yml:

openapi: 3.0.3
info:
  title: Minimal
  version: 1.0.0
paths:
  /thing:
    get:
      summary: Get thing
      responses:
        200:
          description: A thing.
          content:
            application/json:
              schema:
                type: string
                enum:
                  - PENDING
                  - DONE

index.rst:

Page
====

.. openapi:: spec.yml
   :examples:

Actual

$ sphinx-build -W -b html src out
<openapi>:1: WARNING: Lexing literal_block 'HTTP/1.1 200 OK\nContent-Type: application/json\n\nPENDING' as "http" resulted in an error at token: 'P'. Retrying in relaxed mode

The generated example body is the bare token PENDING:

HTTP/1.1 200 OK
Content-Type: application/json

PENDING

Expected

Either a JSON-encoded body, "PENDING", which is a valid JSON document and lexes cleanly, or no example emitted for a scalar schema.

Cause

Two pieces combine, both in sphinxcontrib/openapi/openapi30.py.

_parse_schema returns the raw first enum value, a Python str:

108:    if 'enum' in schema:
109:        # we only show the first one since we can't show everything
110:        return schema['enum'][0]

_example then skips JSON encoding for anything that's already a str:

208:        for example in examples.values():
209:            # According to OpenAPI v3 specs, string examples should be left unchanged
210:            if not isinstance(example['value'], str):
211:                example['value'] = json.dumps(
212:                    example['value'], indent=4, separators=(',', ': '))

The "leave strings unchanged" rule is right for an author-supplied example: value, where the string is meant literally. But a schema-derived example for a type: string schema still needs JSON encoding to be a valid application/json document. The two paths converge on the same isinstance check, so the derived case inherits behavior intended for the literal case.

A fix would need to distinguish schema-derived examples from author-supplied ones, rather than switching on the value's Python type.

Possibly related

All three suggest the example-generation path would benefit from a single place that decides how a derived value becomes a rendered body.

Environment

  • sphinxcontrib-openapi 0.9.0
  • sphinxcontrib-httpdomain 2.0.0
  • Sphinx 8.2.3
  • Pygments 2.20.0
  • docutils 0.21.2
  • Python 3.12.13

Activity

  1. dstrodtman commented on Aug 13, 2026

    @dstrodtman
    ContributorAuthor

    I had a go at the "single place that decides how a derived value becomes a rendered body" idea from the issue, and it does close #168 and #160 as well. Sketching it here before opening a PR, since it touches shared behavior and there are a couple of judgment calls I'd rather you made.

    The shape

    Two small helpers, added to both openapi30.py and openapi31.py:

    def _json_default(value):
        """Render values json cannot serialize on its own."""
        if value is _READONLY_PROPERTY:
            return None
        if isinstance(value, (date, datetime, time)):
            return value.isoformat()
        return str(value)
    
    
    def _dumps(value):
        """Serialize a Python value as the JSON document of an example body."""
        return json.dumps(value, indent=4, separators=(',', ': '),
                          default=_json_default)

    Then in _example, a schema-derived example gets encoded at the point of derivation rather than falling through to the shared type check:

    example = _parse_schema(content['schema'], method=method)
    
    if example is _READONLY_PROPERTY:
        # Nothing in the schema is part of a request, so there's no body to show.
        continue
    
    example = _dumps(example)

    and the existing loop becomes example['value'] = _dumps(example['value']).

    The provenance distinction the issue asks for ends up being expressed by when encoding happens rather than by a flag. A derived value is encoded immediately, so by the time it reaches the isinstance(..., str) check it's already a JSON document and is correctly left alone. An author-supplied value still hits that check, so "string examples are left unchanged" keeps applying to exactly the case it was written for.

    What each issue gets

    Verified with the reproducers from each issue: all three fail on master and build clean under -W with this applied. The existing suite passes unchanged — no committed expectation asserts the old unencoded output, so this doesn't silently rewrite anyone's fixtures.

    The judgment calls

    1. One PR or three? This is one behavioral change in one function, so a single PR with three regression tests seems more reviewable than three PRs touching the same lines in sequence. Happy to split if you'd rather keep the issues independent.

    2. str() as the catch-all. The last line of _json_default means an unexpected type renders as its repr-ish string instead of failing the build. For a docs extension I'd rather render something odd than crash, but it does mean a future unserializable value gets papered over instead of reported. A LOG.warning alongside it would be easy to add if you'd prefer that.

    3. Arrays of read-only items. A request body of type: array whose items are readOnly currently produces [_READONLY_PROPERTY], which crashes the same way Unable to render examples with only readonly properties #160 does. With the sentinel mapped to None it renders [null]. That's valid JSON and no longer a crash, but [] or omitting the example entirely might read better. _parse_schema already filters the sentinel out of object properties but not out of array items, so this is the one place the two disagree.

    4. Sub-second precision. isoformat() on the value YAML parsed from 2000-01-23T04:56:07.000+00:00 gives 2000-01-23T04:56:07+00:00 — the trailing zeros are gone, because they were already gone once YAML parsed it. Faithful to the parsed value, not to the source text. I don't think it's worth chasing, but flagging it.

    5. The duplication. openapi30.py and openapi31.py are near-identical here, so the fix has to land twice. I've mirrored it rather than factoring out a shared module, on the assumption you'd want that as its own change if at all.

    If the shape looks right I'll open the PR. For context on where this came from: the Ray docs are moving their API reference onto this extension, and this is the one of the three issues I filed that blocks using :examples: with an enum-typed response at all.

  2. dstrodtman commented on Oct 13, 2026

    @dstrodtman
    ContributorAuthor

    A correction to my sketch above. It patches openapi30.py and openapi31.py, which only the old renderer uses. The reproducer in this issue uses :examples:, so it goes through that path too, and the sketch is still the right fix for it.

    The new renderer has the same bug in a different place. renderers/_httpdomain.py skips JSON encoding for any str example, at the two if not isinstance(example, str) checks. That's the path Ray actually uses, and #185 already fixes it there.

    So what's left here is the old-renderer fix, along with the old-renderer instances of #168 and #160, which come from the same lines. I haven't checked whether those two also reproduce on the new renderer. Is that fix still worth landing, given the old renderer is the legacy path? If yes, I'll open one PR with a commit per issue, each with its own regression test. If you'd rather leave the old renderer alone, I'll note that here and leave it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions