Repository navigation
Description
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: demoActual (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 calledvalueis still the payload. Check property presence rather than truthiness so validnull,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@opExampleper representable entry, using the Example Object'svalueas 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.exampleandexamplesare 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
examplesmap named on re-emission. Today the emitter uses the decorator'stitleas both the map key and the emittedsummary, and it carriesdescriptionseparately. For example,examples: { small: { summary: "Compact widget", value: ... } }has a key distinct from its summary. Prefer keeping the original key stable (usesmallastitlewith today's emitter), preservedescription, 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
contententry independently, even when two media types use the same schema or the same named-example key. For example,200withapplication/jsonandapplication/vnd.example+json, each with an example namedsmall, should re-emitsmallin 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
200and404), generated models for$refresponses, and responses with required headers. Do not invent header values just to satisfy the return type. For2XX/defaultbranches, 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 readingvalue, keeping the key from the referencing media type's map. An unresolved$ref,externalValuewithout 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 withoutvalue(such asdataValue/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
github-actions commentedon Nov 20, 2026
🎯 Issue Triage
tsp-openapi3drops valid response Media Type Objectexample/examplesvalues instead of importing them as@opExample.returnType, causing payload examples to be lost during round trips.Category: Bug
Area:
openapi3:converter📋 Reproduction code
🔍 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
exampleand namedexamplesinto branch-correct@opExample.returnTypedecorators.baywet commentedon Nov 20, 2026
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-codingbodyor deciding whether to wrap based on the status code.For example, given the OpenAPI payload
{"body":"hello","id":1}and aMessagemodel with ordinarybodyandidproperties:returnTypeexample valueMessagedirectly#{ body: "hello", id: 1 }{ @body payload: Message }(implicit200, 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/@bodyRootand@statusCodeare independent: an explicit body can exist without an explicit status, and an explicit status doesn't imply a body wrapper. The keybodyinside the OpenAPI payload must remain ordinary data even when the generated wrapper is also namedbody(the example will then have two levels:#{ body: #{ body: "hello", id: 1 } }). Likewise, only a property marked@statusCodeshould 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-
bodywrapper name and, where generated, an@bodyRootwrapper) and assert both the response status and the exact re-emitted JSON. The existing emitter tests for@bodyand@bodyRootwithout@statusCodedemonstrate the unwrapping behavior the converter should target.baywet commentedon Nov 20, 2026
A concrete follow-up for multiple media types under the same response status: I verified in TypeSpec 1.18.0 that two
@opExamplevalues can target different media types even when the response bodies have the exact same TypeSpec type and neither example specifies a status code:When emitted as OpenAPI 3.2, these land at
responses["200"].content["application/json"].exampleandresponses["200"].content["text/plain"].example, respectively. Neither emitted payload includesformator thepayloadwrapper.For import, bind each example to its source response key and
contentkey before building thereturnTypevalue. If the generated response has aContent-Typediscriminator, set its actual TypeSpec property (hereformat) 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 firstcontententry, 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.