Skip to content

tsp-openapi3: import response media type examples as @opExample returnType #12627

Description

@baywet

Problem

tsp-openapi3 converts the response schemas and status codes, but silently drops examples on response Media Type Objects (paths.<path>.<verb>.responses.<status>.content.<media-type>.example or .examples). As a result, converting OpenAPI to TypeSpec and emitting OpenAPI again loses those payload examples. The emitter already supports response payload examples authored as @opExample(#{ returnType: ... }); the missing step is the import.

This is a focused piece of the broader example-import request in #3866. The current schema-array PR, #12626, explicitly leaves Media Type Object examples out of scope. Request examples (@opExample.parameters), schema examples (@example), and parameter/header examples are separate work. The SSE emission bug in #11090 is also separate.

Minimal reproduction

Save this as response-examples.yaml and run npx --package @typespec/openapi3@1.18.0 tsp-openapi3 response-examples.yaml --output-dir converted:

openapi: 3.0.3
info:
  title: Widget API
  version: 1.0.0
paths:
  /widgets:
    post:
      operationId: createWidget
      responses:
        '201':
          description: Created
          content:
            application/json:
              schema:
                type: object
                required: [name]
                properties:
                  name:
                    type: string
              example:
                name: demo

Actual (1.18.0): The generated TypeSpec represents the 201 response and its body schema, but has no @opExample. The demo value is lost on re-emission.

Expected: Generate a decorator equivalent to the following (the exact property names and wrapper should follow the generated return type):

@opExample(#{ returnType: #{ statusCode: 201, body: #{ name: "demo" } } })

Re-emitting should place { name: "demo" } at responses["201"].content["application/json"].example, beside schema. The status and content-type values are routing metadata, not part of the serialized payload. 201 is just the example here: 200, errors such as 404, and other supported responses should work too. A plain 200 may use a body-only return type and therefore need a different example shape.

Suggested behavior and edge cases

  • Singular example: Treat it as one raw payload with no title. A payload that happens to be an array is one example, not one per item. Likewise, an object containing a field called value is still the payload. Check property presence rather than truthiness so valid null, false, 0, and empty-string examples are not dropped. Validate or convert values against the generated return type, including scalar and array bodies, rather than producing TypeSpec that fails to compile.
  • Named examples: Import one @opExample per representable entry, using the Example Object's value as the payload. Preserve distinct entries even when their payloads are identical; use deterministic traversal and do not collapse entries into a single decorator. An empty map produces no decorators. example and examples are mutually exclusive on a Media Type Object; if both are present in malformed input, diagnose the conflict and use a documented precedence (or skip that media type), rather than quietly merging both.
  • Map keys and metadata: Keep a one-entry examples map named on re-emission. Today the emitter uses the decorator's title as both the map key and the emitted summary, and it carries description separately. For example, examples: { small: { summary: "Compact widget", value: ... } } has a key distinct from its summary. Prefer keeping the original key stable (use small as title with today's emitter), preserve description, and document the summary fidelity limitation unless there is a separate way to retain both. Do not let two entries with the same summary overwrite one another.
  • Multiple media types under one status: Process each content entry independently, even when two media types use the same schema or the same named-example key. For example, 200 with application/json and application/vnd.example+json, each with an example named small, should re-emit small in both maps with their respective values. Include the generated content-type discriminator wherever necessary to route to the specific media type; do not rely on payload shape, map iteration order, or the default JSON branch. If the generated type cannot express an unambiguous selection, report that rather than attaching the example to the wrong media type or duplicating it.
  • Multiple response statuses and metadata: Build the example against the actual generated response branch, including its body wrapper and status discriminator when present. Cover overlapping body shapes (e.g. the same schema for 200 and 404), generated models for $ref responses, and responses with required headers. Do not invent header values just to satisfy the return type. For 2XX/default branches, retain the original response key where expressible; don't guess a concrete status or spread the example to other branches. Diagnose unsupported or ambiguous cases.
  • References and unsupported values: Resolve supported Example Object $refs (e.g. #/components/examples/SmallWidget) before reading value, keeping the key from the referencing media type's map. An unresolved $ref, externalValue without an inline value, or a payload that cannot be represented in the generated type should not become an example containing a URL, null, or a guessed string. Surface a diagnostic and continue importing other valid examples. A first pass can focus on concrete inline values and resolvable local references without fetching external example content. OpenAPI 3.2 stream/item examples and Example Object forms without value (such as dataValue/serializedValue) can be called out separately if they aren't supported in the first pass.

Verification

Add converter tests that check the generated TypeSpec compiles, and round-trip tests that assert the exact status → media type → example key/value placement. In particular, cover singular vs. single-entry named vs. multi-entry named input, multiple media types with the same schema and reused example names, multiple statuses with overlapping body types, falsy/null and array payloads, and an unsupported example alongside a valid one. Assert that no example leaks to another response/media type or becomes a schema-level @example.

The response expression generator already determines the body and routing shape for each media type (converter). The emitter's response-example tests demonstrate the target behavior for existing @opExample.returnType values, including examples for different statuses on the same operation.

Activity

  1. added
    bugSomething isn't working
    openapi3:converterIssues for @typespec/openapi3 openapi to typespec converter
    on Nov 20, 2026
  2. github-actions commented on Nov 20, 2026

    @github-actions
    Contributor

    🎯 Issue Triage

    tsp-openapi3 drops valid response Media Type Object example/examples values instead of importing them as @opExample.returnType, causing payload examples to be lost during round trips.

    Category: Bug

    Area: openapi3:converter

    📋 Reproduction code
    openapi: 3.0.3
    info:
      title: Widget API
      version: 1.0.0
    paths:
      /widgets:
        post:
          operationId: createWidget
          responses:
            '201':
              description: Created
              content:
                application/json:
                  schema:
                    type: object
                    required: [name]
                    properties:
                      name:
                        type: string
                  example:
                    name: demo
    🔍 Analysis

    The affected path is response generation in the OpenAPI-to-TypeSpec converter. It currently builds response status/body/media-type routing but does not translate Media Type Object examples into return-type examples. The implementation must construct values matching the generated response branch, including status and content-type discriminators, without treating routing metadata as payload data.

    #3866 is the broader example-import request. #12626 handles schema-level example arrays and explicitly excludes Media Type Objects; #11090 is a separate OpenAPI 3.2 SSE emitter issue. No stronger duplicate was found.

    📝 Suggested next steps
    • Import singular example and named examples into branch-correct @opExample.returnType decorators.
    • Diagnose ambiguous branches, conflicting fields, unresolved references, and unrepresentable values without dropping other valid examples.
    • Add compile and round-trip tests across statuses, media types, named/falsy/array payloads, and routing isolation.

    Generated by Agentic Triage

  3. baywet commented on Nov 20, 2026

    @baywet
    MemberAuthor

    One import-sequencing detail worth making explicit: resolve the generated response branch before constructing @opExample.returnType. The OpenAPI example is the wire payload; the TypeSpec example must match the generated operation's return value. Use the same response-shape information that generates the return type (including property names/paths after sanitization), rather than hard-coding body or deciding whether to wrap based on the status code.

    For example, given the OpenAPI payload {"body":"hello","id":1} and a Message model with ordinary body and id properties:

    Generated TypeSpec return shape returnType example value
    Message directly #{ body: "hello", id: 1 }
    { @body payload: Message } (implicit 200, no @statusCode) #{ payload: #{ body: "hello", id: 1 } }
    { @statusCode code: 201; @body payload: Message } #{ code: 201, payload: #{ body: "hello", id: 1 } }
    { @statusCode code: 201; body: string; id: int32 } (implicit body) #{ code: 201, body: "hello", id: 1 }

    All four should re-emit the same payload at their corresponding response status. @body/@bodyRoot and @statusCode are independent: an explicit body can exist without an explicit status, and an explicit status doesn't imply a body wrapper. The key body inside the OpenAPI payload must remain ordinary data even when the generated wrapper is also named body (the example will then have two levels: #{ body: #{ body: "hello", id: 1 } }). Likewise, only a property marked @statusCode should be populated from the OpenAPI response key; a same-named field in the payload is just data.

    Suggested regression coverage: compile the generated TypeSpec for the shapes above (including a non-body wrapper name and, where generated, an @bodyRoot wrapper) and assert both the response status and the exact re-emitted JSON. The existing emitter tests for @body and @bodyRoot without @statusCode demonstrate the unwrapping behavior the converter should target.

  4. baywet commented on Nov 20, 2026

    @baywet
    MemberAuthor

    A concrete follow-up for multiple media types under the same response status: I verified in TypeSpec 1.18.0 that two @opExample values can target different media types even when the response bodies have the exact same TypeSpec type and neither example specifies a status code:

    import "@typespec/http";
    using TypeSpec.Http;
    
    @opExample(#{ returnType: #{ format: "application/json", payload: "json example" } })
    @opExample(#{ returnType: #{ format: "text/plain", payload: "plain example" } })
    @get op read(): {
      @header("content-type") format: "application/json" | "text/plain";
      @body payload: string;
    };

    When emitted as OpenAPI 3.2, these land at responses["200"].content["application/json"].example and responses["200"].content["text/plain"].example, respectively. Neither emitted payload includes format or the payload wrapper.

    For import, bind each example to its source response key and content key before building the returnType value. If the generated response has a Content-Type discriminator, set its actual TypeSpec property (here format) to the source media type. This works independently of @statusCode. If a generated branch has no content-type property (e.g. an implicit JSON branch), use that branch's actual shape; don't invent a discriminator property. Don't infer the media type from the body value or schema, default to the first content entry, or copy a single example to sibling media types. If the generated shape can't distinguish the intended destinations, diagnose the ambiguity rather than silently misrouting an example.

    For named examples, emit one decorator per entry with the same media-type selection, and scope keys to each status/media-type pair. A useful round-trip test is two media types with the same body schema, multiple named examples in one media type, and at least one key reused across both. Assert the exact example keys and values under each media type and that no examples leak across them.

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

Metadata

Metadata

Labels

bugSomething isn't workingopenapi3:converterIssues for @typespec/openapi3 openapi to typespec converter

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions