OpenAPI3与Swagger:如何跨组件参数/组件引用描述内容?
Hey there, let's break down why your description $ref is throwing an error and how to fix this properly.
Why schema $ref works but description doesn't
The core issue here is that $ref is only supported in specific fields defined by the OpenAPI specification — mainly fields that accept JSON Schema objects (like schema). The description field is a plain string type, so when you pass a $ref (which is an object like {"$ref": "..."}) to it, Swagger's validator correctly flags it as a type mismatch (it expects a string, but gets an object instead).
In contrast, the schema field is built to handle JSON Schema constructs, and $ref is a valid JSON Schema keyword for referencing reusable schemas — that’s why that part of your code works without issues.
Solutions to reuse descriptions
1. Reuse a parameter's description (your exact use case)
For YAML-based OpenAPI docs, the simplest way to reuse string values like descriptions is to use YAML native anchors and aliases. This works because YAML resolves these during parsing, so the final description becomes a plain string that fully complies with OpenAPI rules.
Here's how to adjust your example:
components: parameters: comparam01: in: query name: comparam01 schema: type: string description: ¶mDesc Any text. # Define an anchor for the description comparam02: in: query name: comparam02 schema: $ref: '#/components/parameters/comparam01/schema' description: *paramDesc # Use the alias to reuse the anchored string
2. Reuse descriptions across different component types
If you need to reuse a description from one component type (like a schema) to another (like a parameter), the same YAML anchor approach applies. Just define the anchor on the source description and reference it with the alias wherever you need it:
components: schemas: User: type: object description: &userDesc Represents a registered platform user. properties: id: type: integer parameters: userId: in: path name: userId required: true schema: type: integer description: *userDesc # Reuse the schema's description here
Important Notes
- If you’re working with JSON instead of YAML, you don’t get native anchor support. In that case, you’ll need to either:
- Manually duplicate the description text, or
- Use a preprocessing script (like a Node.js script or specialized OpenAPI tooling) to inject reused strings before validating the document.
- Even OpenAPI 3.1 (which aligns more closely with JSON Schema 2020-12) doesn’t allow
$refin string fields likedescription— $ref remains reserved for referencing schema objects.
内容的提问来源于stack exchange,提问作者Michael

