### Serialization and Examples
Source: https://github.com/oai/openapi-specification/blob/main/versions/3.2.0.md
Guidelines for presenting serialized API parameter and header examples, including delimiters and encoding.
```APIDOC
## Serialization and Examples
### Description
These rules apply to both Parameter and [Header](#header-object) Objects, which share serialization mechanisms. Examples should show the fully encoded/escaped value, including any delimiters generated by `style` and `explode` configurations.
### Including Names and Delimiters
* For `name=value` pairs (e.g., `style: "form"`) or `style: "simple", explode: true`, the name and any delimiter between the name and value MUST be included in examples.
* `matrix` and `label` styles produce a leading delimiter that MUST be included.
* RFC6570 operators for `style: "form"` produce `?` or `&`. This leading delimiter MUST NOT be included in examples of individual parameters or media type documents, as its suitability depends on context.
* For `in: "cookie", style: "form"`, neither `&` nor `?` delimiters are correct. Refer to [Appendix D](#appendix-d-serializing-headers-and-cookies).
### Header Serialization
* Header names are generally NOT included in serialization examples, as they are not part of the RFC6570-derived result.
* Exception: Names produced by `style: "simple", explode: "true"` are included within the header value.
* Special rules apply to `Set-Cookie` response headers; see the [Header Object](#header-object).
```
--------------------------------
### Define Models with Examples
Source: https://github.com/oai/openapi-specification/blob/main/versions/3.2.0.md
Provides an example of how to attach sample data to a schema definition to assist API consumers in understanding the expected payload structure.
```yaml
type: object
properties:
id:
type: integer
format: int64
name:
type: string
required:
- name
examples:
- name: Puma
id: 1
```
--------------------------------
### Request Body Examples in OpenAPI
Source: https://github.com/oai/openapi-specification/blob/main/versions/3.2.0.md
Shows how to define examples for a request body across multiple media types. It demonstrates referencing external example files using `externalValue` for JSON, XML, and plain text formats, as well as a wildcard `*/*` example.
```yaml
description: user to add to the system
content:
application/json:
schema:
$ref: '#/components/schemas/User'
examples:
user:
summary: User example
externalValue: https://foo.bar/examples/user-example.json
application/xml:
schema:
$ref: '#/components/schemas/User'
examples:
user:
summary: User example in XML
externalValue: https://foo.bar/examples/user-example.xml
text/plain:
examples:
user:
summary: User example in plain text
externalValue: https://foo.bar/examples/user-example.txt
'*/*':
examples:
user:
summary: User example in other format
externalValue: https://foo.bar/examples/user-example.whatever
```
--------------------------------
### Tag Object Specification Example (YAML)
Source: https://github.com/oai/openapi-specification/blob/main/proposals/2024-09-01-Tags-Improvement.md
Presents an example of the Tag Object structure in YAML format, aligning with the proposed OpenAPI specification updates. This example showcases 'name', 'summary', 'description', 'parent', and 'kind' for tag definition.
```yaml
- name: account-updates
summary: Account Updates
description: Account update operations
kind: nav
- name: partner
summary: Partner
description: Operations available to the partners network
parent: external
kind: audience
- name: external
summary: External
description: Operations available to external consumers
kind: audience
```
--------------------------------
### HTTP Request Example for Callback Evaluation
Source: https://github.com/oai/openapi-specification/blob/main/versions/3.2.0.md
An example HTTP POST request demonstrating the structure and content that can be used to evaluate runtime expressions for callback operations.
```http
POST /subscribe/myevent?queryUrl=https://clientdomain.com/stillrunning HTTP/1.1
Host: example.org
Content-Type: application/json
Content-Length: 188
{
"failedUrl": "https://clientdomain.com/failed",
"successUrls": [
"https://clientdomain.com/fast",
"https://clientdomain.com/medium",
"https://clientdomain.com/slow"
]
}
```
--------------------------------
### Define Binary Examples via External Reference
Source: https://github.com/oai/openapi-specification/blob/main/versions/3.2.0.md
Shows how to reference external binary files, such as images, using the externalValue property in an OpenAPI example object.
```yaml
content:
image/png:
schema: {}
examples:
Red:
externalValue: ./examples/2-by-2-red-pixels.png
```
--------------------------------
### Define JSON Examples in OpenAPI
Source: https://github.com/oai/openapi-specification/blob/main/versions/3.2.0.md
Demonstrates how to define JSON examples within an OpenAPI schema using both dataValue for structured data and serializedValue for string-based representations.
```yaml
content:
application/json:
schema:
type: object
required:
- author
- title
properties:
author:
type: string
title:
type: string
rating:
type: number
minimum: 1
maximum: 5
multipleOf: 0.5
examples:
noRating:
summary: A not-yet-rated work
dataValue:
author: A. Writer
title: The Newest Book
withRating:
summary: A work with an average rating of 4.5 stars
dataValue:
author: A. Writer
title: An Older Book
rating: 4.5
serializedValue: |
{
"author": "A. Writer",
"title": "An Older Book",
"rating": 4.5
}
```
--------------------------------
### Example Object Definition
Source: https://github.com/oai/openapi-specification/blob/main/versions/3.2.0.md
Defines the structure and fields of an Example Object used in OpenAPI specifications.
```APIDOC
## Example Object
### Description
An object grouping an internal or external example value with basic `summary` and `description` metadata. The examples can show either data suitable for schema validation, or serialized data as required by the containing [Media Type Object](#media-type-object), [Parameter Object](#parameter-object), or [Header Object](#header-object).
### Fixed Fields
| Field Name | Type | Description |
| ---- | :----: | ---- |
| summary | `string` | Short description for the example. |
| description | `string` | Long description for the example. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. |
| dataValue | Any | An example of the data structure that MUST be valid according to the relevant [Schema Object](#schema-object). If this field is present, `value` MUST be absent. |
| serializedValue | `string` | An example of the serialized form of the value, including encoding and escaping as described under [Validating Examples](#validating-examples). If `dataValue` is present, then this field SHOULD contain the serialization of the given data. Otherwise, it SHOULD be the valid serialization of a data value that itself MUST be valid as described for `dataValue`. This field SHOULD NOT be used if the serialization format is JSON, as the data form is easier to work with. If this field is present, `value`, and `externalValue` MUST be absent. |
| externalValue | `string` | A URI that identifies the serialized example in a separate document, allowing for values not easily or readably expressed as a Unicode string. If `dataValue` is present, then this field SHOULD identify a serialization of the given data. Otherwise, the value SHOULD be the valid serialization of a data value that itself MUST be valid as described for `dataValue`. If this field is present, `serializedValue` and `value` MUST be absent. See also the rules for resolving [Relative References](#relative-references-in-api-description-uris). |
| value | Any | Embedded literal example. The `value` field and `externalValue` field are mutually exclusive. To represent examples of media types that cannot naturally be represented in JSON or YAML, use a string value to contain the example, escaping where necessary.
**Deprecated for non-JSON serialization targets:** Use `dataValue` and/or `serializedValue`, which both have unambiguous syntax and semantics, instead. |
### Usage
Example Objects can be used in [Parameter Objects](#parameter-object), [Header Objects](#header-object), and [Media Type Objects](#media-type-object) through the `examples` (plural) field. The `example` (singular) field is a shorthand alternative.
### Considerations
- The `value` field and `externalValue` field are mutually exclusive.
- `dataValue` and `serializedValue` are mutually exclusive with `value` and `externalValue`.
- Tooling implementations MAY choose to validate compatibility between the example value and the schema automatically.
```
--------------------------------
### Define OpenAPI Example Objects using YAML and JSON
Source: https://github.com/oai/openapi-specification/blob/main/versions/3.2.0.md
Demonstrates how to structure the 'examples' field in an OpenAPI specification. It shows both native YAML object representation and the use of JSON syntax within a YAML document for the 'value' property.
```yaml
application/json:
schema:
$ref: '#/components/schemas/Pet'
examples:
cat:
summary: An example of a cat
value:
name: Fluffy
petType: Cat
color: White
gender: male
breed: Persian
dog:
summary: An example of a dog with a cat's name
value:
name: Puma
petType: Dog
color: Black
gender: Female
breed: Mixed
frog:
$ref: '#/components/examples/frog-example'
```
```yaml
application/json:
schema:
$ref: '#/components/schemas/Pet'
examples:
cat:
summary: An example of a cat
value: {
"name": "Fluffy",
"petType": "Cat",
"color": "White",
"gender": "male",
"breed": "Persian"
}
dog:
summary: An example of a dog with a cat's name
value: {
"name": "Puma",
"petType": "Dog",
"color": "Black",
"gender": "Female",
"breed": "Mixed"
}
frog:
$ref: '#/components/examples/frog-example'
```
--------------------------------
### Model with Example
Source: https://github.com/oai/openapi-specification/blob/main/versions/3.2.0.md
Defines a model that includes example data directly within its schema definition, providing concrete instances of the expected structure.
```APIDOC
## Model with Example
### Description
Defines an object schema that includes one or more examples of valid data. This helps consumers understand the expected structure and content.
### Method
N/A (Schema Definition)
### Endpoint
N/A (Schema Definition)
### Parameters
#### Path Parameters
N/A
#### Query Parameters
N/A
#### Request Body
- **id** (integer) - Optional - A unique identifier for the item.
- **name** (string) - Required - The name of the item.
- **examples** (array) - Optional - An array of example objects conforming to the schema.
- **name** (string) - Example name.
- **id** (integer) - Example ID.
### Request Example
```json
{
"id": 1,
"name": "Puma"
}
```
### Response
#### Success Response (200)
- **id** (integer) - A unique identifier for the item.
- **name** (string) - The name of the item.
#### Response Example
```json
{
"id": 1,
"name": "Puma"
}
```
```
--------------------------------
### HTTP Response Example for Callback Evaluation
Source: https://github.com/oai/openapi-specification/blob/main/versions/3.2.0.md
An example HTTP response that might be generated after a request, used to evaluate runtime expressions for callback operations.
```http
201 Created
Location: https://example.org/subscription/1
```
--------------------------------
### OpenAPI Operation with Links Object Example
Source: https://github.com/oai/openapi-specification/blob/main/versions/3.2.0.md
An example of a 'GET /users/{id}' operation that includes a 'links' object. The 'address' link uses the 'operationId' and passes a request path parameter.
```yaml
paths:
/users/{id}:
parameters:
- name: id
in: path
required: true
description: the user identifier, as userId
schema:
type: string
get:
responses:
'200':
description: the user being returned
content:
application/json:
schema:
type: object
properties:
uuid:
type: string
format: uuid
links:
address:
operationId: getUserAddress
parameters:
userid: $request.path.id
```
--------------------------------
### OpenAPI Server Object Example (YAML)
Source: https://github.com/oai/openapi-specification/blob/main/versions/3.2.0.md
Describes a single server object with its URL, description, and name.
```yaml
url: https://development.gigantic-server.com/v1
description: Development server
name: dev
```
--------------------------------
### OpenAPI Server Object Example (YAML)
Source: https://github.com/oai/openapi-specification/blob/main/versions/3.2.0.md
An example of the Server object in OpenAPI Specification, defining a URL to the target host, an optional description, name, and a map of server variables for substitution in the URL template.
```yaml
url: https://api.example.com/{version}
description: The production API server.
variables:
version:
default: v1
enum:
- v1
- v2
```
--------------------------------
### Standard Header Serialization Examples
Source: https://github.com/oai/openapi-specification/blob/main/versions/3.2.0.md
Demonstrates the interchangeability of multi-line and comma-separated single-line forms for standard HTTP headers.
```http
Accept-Encoding: compress;q=0.5
Accept-Encoding: gzip;q=1.0
```
```http
Accept-Encoding: compress;q=0.5,gzip;q=1.0
```
--------------------------------
### Example Tag Structure in OpenAPI (YAML)
Source: https://github.com/oai/openapi-specification/blob/main/proposals/2024-09-01-Tags-Improvement.md
Demonstrates the proposed structure for tags within an OpenAPI specification using YAML. It includes examples of 'name', 'kind', 'summary', 'description', and 'parent' fields for hierarchical and categorized tags.
```yaml
tags:
- name: deprecated
kind: internal
summary: Deprecated
description: This operation has been deprecated and will be removed in the future. Avoid using items with this tag.
- name: shop
kind: nav
summary: Order Online
description: Operations relating to the retail operations behind the [online shopping site](https://example.com/shopping).
- name: products
kind: nav
parent: shop
summary: Products
description: View and manage the product catalog.
- name: orders
kind: nav
parent: shop
summary: Online Orders
description: Place, fulfil and invoice orders for the online shop.
```
--------------------------------
### OpenAPI Multiple Server Objects Example (YAML)
Source: https://github.com/oai/openapi-specification/blob/main/versions/3.2.0.md
Demonstrates how to define multiple server objects within the OpenAPI Object's `servers` array.
```yaml
servers:
- url: https://development.gigantic-server.com/v1
description: Development server
name: dev
- url: https://staging.gigantic-server.com/v1
description: Staging server
name: staging
- url: https://api.gigantic-server.com/v1
description: Production server
name: prod
```
--------------------------------
### Security Requirement Object Examples
Source: https://github.com/oai/openapi-specification/blob/main/versions/3.2.0.md
Illustrates how to define security requirements for API operations. This includes examples for API key authentication and OAuth2 scopes, specifying which security schemes must be satisfied.
```yaml
api_key: []
```
```yaml
petstore_auth:
- write:pets
- read:pets
```
--------------------------------
### Multiple Alternative Schema Versions Example (YAML)
Source: https://github.com/oai/openapi-specification/blob/main/proposals/Alternative-Schema/examples.md
Illustrates how to define multiple, distinct alternative schema versions for a single schema using an `anyOf` construct, each specified with its type and location.
```yaml
schema:
anyOf:
- x-oas-draft-alternativeSchema:
type: jsonSchema
location: "./real-jsonschema-08.json"
- x-oas-draft-alternativeSchema:
type: jsonSchema
location: "./real-jsonschema-07.json"
```
--------------------------------
### Setup Respec for Local Viewing
Source: https://github.com/oai/openapi-specification/blob/main/tests/md2html/README.md
Use this command to set up the Respec JavaScript file and create a gitignore for local viewing of HTML files.
```sh
mkdir js
cp ../../node_modules/respec/builds/respec-w3c.js js/
echo "*" > js/.gitignore
```
--------------------------------
### Tag Object Specification Example (JSON)
Source: https://github.com/oai/openapi-specification/blob/main/proposals/2024-09-01-Tags-Improvement.md
Provides an example of the Tag Object structure in JSON format as per the updated OpenAPI specification. It illustrates the 'name', 'summary', 'description', 'parent', and 'kind' fields for defining tag metadata.
```json
{
"name": "account-updates",
"summary": "Account Updates",
"description": "Account update operations",
"kind": "nav"
},
{
"name": "partner",
"summary": "Partner",
"description": "Operations available to the partners network",
"parent": "external",
"kind": "audience"
},
{
"name": "external",
"summary": "External",
"description": "Operations available to external consumers",
"kind": "audience"
}
```
--------------------------------
### OpenAPI Info Object Example (YAML)
Source: https://github.com/oai/openapi-specification/blob/main/versions/3.2.0.md
An example of the Info object in OpenAPI Specification, used to provide metadata about the API, including its title, summary, description, terms of service, contact information, license, and version.
```yaml
title: Example Pet Store App
summary: A pet store manager.
description: This is an example server for a pet store.
termsOfService: https://example.com/terms/
contact:
name: API Support
url: https://www.example.com/support
email: support@example.com
license:
name: Apache 2.0
url: https://www.apache.org/licenses/LICENSE-2.0.html
version: 1.0.1
```
--------------------------------
### Example Server-Sent Event Stream Payload
Source: https://github.com/oai/openapi-specification/blob/main/versions/3.2.0.md
Provides a raw text/event-stream example matching the defined schema, showing how events, data fields, and comments are structured in a stream.
```eventstream
event: addString
data: This data is formatted
data: across two lines
retry: 5
event: addInt64
data: 1234.5678
unknownField: this is ignored
: This is a comment
event: addJSON
data: {"foo": 42}
```
--------------------------------
### OpenAPI License Object Example (YAML)
Source: https://github.com/oai/openapi-specification/blob/main/versions/3.2.0.md
An example of the License object in OpenAPI Specification, used to define licensing information for the API, including the license name, an optional SPDX identifier, or a URL to the license.
```yaml
name: Apache 2.0
identifier: Apache-2.0
```
--------------------------------
### Querystring JSONPath Example in OpenAPI
Source: https://github.com/oai/openapi-specification/blob/main/versions/3.2.0.md
Illustrates defining a querystring parameter using JSONPath. It highlights the use of the `application/jsonpath` media type and the shorthand `example` field for providing the JSONPath expression. The `serializedValue` shows the URL-encoded JSONPath.
```yaml
in: querystring
name: selector
content:
application/jsonpath:
schema:
type: string
example: $.a.b[1:1]
examples:
Selector:
serializedValue: "%24.a.b%5B1%3A1%5D"
```
--------------------------------
### operationRef Examples
Source: https://github.com/oai/openapi-specification/blob/main/versions/3.2.0.md
Demonstrates how to use operationRef to reference operations, either relatively or through a non-relative URI, and the necessary escaping for path templates.
```APIDOC
## operationRef Examples
As the `operationId` is an optional field in an [Operation Object](#operation-object), references MAY instead be made through a URI reference with `operationRef`. Note that both of these examples reference operations that can be identified via the [Paths Object](#paths-object) to ensure that the operation's path template is unambiguous.
### Relative URI Reference
A relative URI reference `operationRef`:
```yaml
links:
UserRepositories:
# returns array of '#/components/schemas/repository'
operationRef: '#/paths/~12.0~1repositories~1%7Busername%7D/get'
parameters:
username: $response.body#/username
```
### Non-Relative URI Reference
A non-relative URI `operationRef`:
```yaml
links:
UserRepositories:
# returns array of '#/components/schemas/repository'
operationRef: https://na2.gigantic-server.com/#/paths/~12.0~1repositories~1%7Busername%7D/get
parameters:
username: $response.body#/username
```
**Note:** In the use of `operationRef` the _escaped forward-slash_ (`~1`) is necessary when using JSON Pointer in URI fragments, and it is necessary to URL-encode `{` and `}` as `%7B` and `%7D`, respectively. The unescaped, percent-decoded path template in the above examples would be `/2.0/repositories/{username}`.
```
--------------------------------
### Querystring JSON Example in OpenAPI
Source: https://github.com/oai/openapi-specification/blob/main/versions/3.2.0.md
Demonstrates defining a querystring parameter that accepts JSON. It shows how to specify the schema and provide examples directly within the content object and at the root level. The `dataValue` field illustrates the data structure, while `serializedValue` shows the URL-encoded representation.
```yaml
in: querystring
name: json
content:
application/json:
schema:
type: object
properties:
numbers:
type: array
items:
type: integer
flag:
type: [boolean, "null"]
examples:
TwoNoFlag:
description: Serialize with minimized whitespace
dataValue:
numbers:
- 1
- 2
flag: null
serializedValue: '{"numbers":[1,2],"flag":null}'
examples:
TwoNoFlag:
dataValue:
numbers:
- 1
- 2
flag: null
serializedValue: "%7B%22numbers%22%3A%5B1%2C2%5D%2C%22flag%22%3Anull%7D"
```
--------------------------------
### JavaScript Examples for OpenAPI Parameter Serialization
Source: https://github.com/oai/openapi-specification/blob/main/versions/3.2.0.md
Illustrates how string, array, and object values are represented in the 'dataValue' field for different OpenAPI parameter styles. This is a foundational example for understanding data representation before serialization.
```javascript
string -> "blue"
array -> ["blue", "black", "brown"]
object -> { "R": 100, "G": 200, "B": 150 }
```
--------------------------------
### Combined Different Alternative Schema Types Example (YAML)
Source: https://github.com/oai/openapi-specification/blob/main/proposals/Alternative-Schema/examples.md
Demonstrates combining different types of alternative schemas (e.g., XML Schema and Schematron) using an `allOf` construct, specifying each with its type and location.
```yaml
schema:
allOf:
- x-oas-draft-alternativeSchema:
type: xmlSchema
location: "./xmlSchema.xsd"
- x-oas-draft-alternativeSchema:
type: schematron
location: "./schema.sch"
```
--------------------------------
### Configure XML Attributes, Namespaces, and Prefixes
Source: https://github.com/oai/openapi-specification/blob/main/versions/3.2.0.md
Demonstrates how to map schema properties to XML attributes and apply namespaces with prefixes. The example shows the schema definition and the resulting XML output.
```yaml
components:
schemas:
Person:
type: object
properties:
id:
type: integer
format: int32
xml:
nodeType: attribute
name:
type: string
xml:
namespace: https://example.com/schema/sample
prefix: sample
```
```xml
Awesome documentation goes here
``` -------------------------------- ### XML with Ordered Elements and Null Serialization Source: https://github.com/oai/openapi-specification/blob/main/versions/3.2.0.md Demonstrates how to use `prefixItems` to define the order and types of elements in an XML array, including the serialization of null values. ```APIDOC ## Ordered Elements and Text ### Description Controls the exact order of elements using the `prefixItems` keyword. Requires explicit naming for elements and setting `nodeType: "element"` for the array to represent a sequence. ### Method N/A (Schema Definition) ### Endpoint N/A (Schema Definition) ### Parameters N/A ### Request Example ```yaml application/xml: schema: xml: nodeType: element name: OneTwoThree type: array minLength: 3 maxLength: 3 prefixItems: - xml: name: One type: string - xml: name: Two type: object required: - unit - value properties: unit: type: string xml: nodeType: attribute value: type: number xml: nodeType: text - xml: name: Three type: - boolean - "null" examples: OneTwoThree: dataValue: - Some text - unit: cubits value: 42 - null externalValue: "./examples/OneTwoThree.xml" ``` ### Response #### Success Response (200) N/A (Schema Definition) #### Response Example ```xml