Swagger 2.0(OpenAPI规范)中请求体能否同时指定ref与example?
example and $ref for a request body in Swagger 2.0? Absolutely! In Swagger 2.0, you can define a custom example for a request body that references a schema via $ref—you just need to place the example in the correct hierarchy to make it work (and avoid the common mistake of putting it alongside $ref where it gets ignored).
Here's how it works:
In Swagger 2.0, request bodies are defined as in: body parameters. You can reference a shared schema using schema: $ref, and then add a custom example directly at the parameter level (not inside the schema object). This parameter-level example will override any example defined in the referenced schema, which is exactly what you need for your PUT request scenario where the incoming instance differs from the schema's default example.
Example Implementation
swagger: '2.0' info: title: User Management API version: 1.0.0 definitions: User: type: object properties: id: type: integer name: type: string email: type: string # Schema-level example (will be overridden by the request body's example) example: id: 123 name: "John Doe" email: "john@example.com" paths: /users/{userId}: put: summary: Update an existing user parameters: - name: userId in: path required: true type: integer - name: updatedUser in: body required: true schema: $ref: '#/definitions/User' # Reference the shared schema # Custom request body example (takes precedence over schema's example) example: id: 456 name: "Jane Smith" email: "jane.smith@company.com" responses: 200: description: User updated successfully schema: $ref: '#/definitions/User'
Critical Note: Avoid This Mistake
Don't place the example inside the schema object alongside $ref—Swagger 2.0 ignores all sibling properties of $ref, so that example won't be recognized:
# ❌ Wrong: Example gets ignored because it's a sibling of $ref schema: $ref: '#/definitions/User' example: { ... } # This won't work!
Why It Works For Responses
This logic is identical to how you implement custom examples for responses: you can add an example at the response level (not inside the referenced schema) to override the schema's default example. That's why you saw it working for responses already.
In short: By placing your custom example at the same level as the schema field in your request body parameter, you can use a $ref and a custom instance example together in Swagger 2.0.
内容的提问来源于stack exchange,提问作者m0thra

