API / Swagger Interview questions
What is $ref used for in OpenAPI documents?
$ref is a JSON Reference pointer that lets one part of an OpenAPI document point to a definition located elsewhere, most commonly a reusable schema, parameter, or response defined under components, avoiding duplication of the same structure in multiple places.
paths: /users/{id}: get: responses: '200': content: application/json: schema: $ref: '#/components/schemas/User'
The value of $ref is a JSON Pointer — #/components/schemas/User means "within this document, follow components then schemas then User" — and it can also point to a definition in a completely separate file (e.g. ./schemas/user.yaml#/User), which is the mechanism that makes splitting a large spec across multiple files possible.
A subtlety worth knowing: per the OpenAPI 3.0 specification, when a $ref is used alongside sibling keys in the same object, those sibling keys are technically ignored in favor of following the reference — a common source of confusion when someone tries to add a description next to a $ref expecting it to merge, when in OpenAPI 3.0 it doesn't (OpenAPI 3.1's closer JSON Schema alignment changes this behavior).
More Related questions...