# Property order

Source: https://apigenie.pl/docs/reference/cli/format/property-order
Part of the reference of [format](https://apigenie.pl/docs/reference/cli/format.md).
Its other pages: [Layout and YAML styles](https://apigenie.pl/docs/reference/cli/format/styles.md), [AsyncAPI documents](https://apigenie.pl/docs/reference/cli/format/asyncapi.md), [Swagger 2.0 documents](https://apigenie.pl/docs/reference/cli/format/swagger.md), [Protobuf files](https://apigenie.pl/docs/reference/cli/format/protobuf.md), [GraphQL documents](https://apigenie.pl/docs/reference/cli/format/graphql.md).

The `property_order` key of the `openapi` section of `commands.format` sets the order of the
properties of every kind of OpenAPI object, and of the names in maps such as components, properties
and media types. The `asyncapi` and `swagger` sections have a `property_order` of their own, with the
objects of [AsyncAPI 3](/docs/reference/cli/format/asyncapi#objects) and [Swagger 2.0](/docs/reference/cli/format/swagger#objects).

## Orders

Each key of `property_order` takes one of three orders:

- `original` keeps the order of the input file. It is the default, and the order to keep for a
  document that is edited by hand, because it adds nothing to a diff.
- `sorted` sorts the properties by name. It suits maps whose keys are names: path templates,
  component names, the status codes of responses.
- An array of property names puts the listed properties first, in that order, and the others after
  them in the order of the input file. Fields of later OpenAPI versions and extensions are never
  listed, so they follow the listed ones. A fixed order suits operations and schemas, where
  `summary` and `description` read better first.

The order under `default` applies to every object without an order of its own, and the order under
the name of a kind of object (see [Objects](#objects)) to that kind.

**Example** - Preserve original property order for all schema objects

```yaml
commands:
  format:
    openapi:
      property_order:
        default: original
```

**Example** - Sort all path items within `Paths` objects alphabetically

```yaml
commands:
  format:
    openapi:
      property_order:
        paths: sorted
```

**Example** - Specify custom property order for `Operation` objects

```yaml
commands:
  format:
    openapi:
      property_order:
        operation:
          # place summary and description at the beginning, to help
          # understand operation's purpose
          - summary
          - description
          - tags
          - operationId
          - externalDocs
          - deprecated
          - parameters
          - requestBody
          - responses
          - callbacks
          - security
          - servers
```

**Example**

If the configuration for the `Contact` object looks like:

```yaml
commands:
  format:
    openapi:
      property_order:
        contact:
          - name
          - url
          - email
```

and the actual contact data before formatting looks like:

```yaml
openapi: 3.1.0
info:
  contact:
    x-team: awesome
    name: You
    email: you@example.com
    url: your.site
    x-audience: internal
    x-stability: stable
...
```

formatting it will change it to:

```yaml
openapi: 3.1.0
info:
  contact:
    name: You
    url: your.site
    email: you@example.com
    x-team: awesome
    x-audience: internal
    x-stability: stable
...
```

## Objects

The keys of `property_order`, the objects they name, and the order the `recommended` preset gives
each of them. Each key takes `sorted`, `original` or an array of property names.

| Key                     | Object                                                     | Recommended order                                                                                                                                                       |
| ----------------------- | ---------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `openapi`               | OpenAPI (document root)                                    | openapi, $self, info, jsonSchemaDialect, servers, paths, webhooks, components, security, tags, externalDocs                                                             |
| `info`                  | Info                                                       | title, summary, description, version, termsOfService, contact, license                                                                                                  |
| `contact`               | Contact                                                    | name, url, email                                                                                                                                                        |
| `license`               | License                                                    | name, identifier, url                                                                                                                                                   |
| `server`                | Server                                                     | url, name, description, variables                                                                                                                                       |
| `serverVariable`        | Server Variable                                            | description, default, enum                                                                                                                                              |
| `paths`                 | Paths (the path templates)                                 | sorted                                                                                                                                                                  |
| `pathItem`              | Path Item (in paths, webhooks, callbacks and components)   | $ref, summary, description, parameters, get, post, put, patch, delete, query, options, head, trace, additionalOperations, servers                                       |
| `operation`             | Operation (also `query` and `additionalOperations`)        | tags, summary, operationId, description, externalDocs, deprecated, parameters, requestBody, responses, callbacks, security, servers                                      |
| `components`            | Components                                                 | schemas, responses, parameters, requestBodies, headers, mediaTypes, pathItems, securitySchemes, links, callbacks, examples                                               |
| `externalDocumentation` | External Documentation (also of schemas)                   | description, url                                                                                                                                                        |
| `parameter`             | Parameter                                                  | name, in, description, required, deprecated, style, allowEmptyValue, explode, allowReserved, schema, content, example, examples                                          |
| `requestBody`           | Request Body                                               | description, required, content                                                                                                                                          |
| `mediaType`             | Media Type                                                 | description, schema, itemSchema, encoding, prefixEncoding, itemEncoding, example, examples                                                                              |
| `encoding`              | Encoding                                                   | contentType, style, headers, explode, allowReserved, encoding, prefixEncoding, itemEncoding                                                                             |
| `responses`             | Responses (the status codes of an operation)               | sorted                                                                                                                                                                  |
| `response`              | Response                                                   | summary, description, headers, content, links                                                                                                                           |
| `example`               | Example                                                    | summary, description, dataValue, serializedValue, value, externalValue                                                                                                  |
| `link`                  | Link                                                       | description, server, operationRef, operationId, parameters, requestBody                                                                                                 |
| `header`                | Header                                                     | name, description, required, deprecated, allowEmptyValue, style, explode, allowReserved, schema, content, example, examples                                              |
| `tag`                   | Tag                                                        | name, summary, description, parent, kind, externalDocs                                                                                                                  |
| `reference`             | Reference (see below)                                      | $ref, summary, description                                                                                                                                              |
| `schema`                | Schema, at any depth                                       | $schema, $id, $anchor, $dynamicAnchor, $ref, $dynamicRef, title, description, $comment, type, format, nullable, const, enum, numeric, string, array and object keywords, allOf, oneOf, anyOf, not, if, then, else, default, examples, example, readOnly, writeOnly, deprecated, discriminator, xml, externalDocs, $defs, definitions |
| `discriminator`         | Discriminator                                              | propertyName, mapping, defaultMapping                                                                                                                                   |
| `xml`                   | XML                                                        | nodeType, name, namespace, prefix, attribute, wrapped                                                                                                                   |
| `securityScheme`        | Security Scheme                                            | name, description, type, in, scheme, bearerFormat, flows, openIdConnectUrl, oauth2MetadataUrl, deprecated                                                               |
| `oauthFlows`            | OAuth Flows                                                | implicit, password, clientCredentials, authorizationCode, deviceAuthorization                                                                                           |
| `oauthFlow`             | OAuth Flow                                                 | authorizationUrl, deviceAuthorizationUrl, tokenUrl, refreshUrl, scopes                                                                                                  |
| `componentNames`        | The names in each map of Components                        | default                                                                                                                                                                 |
| `webhooks`              | The names of webhooks                                      | default                                                                                                                                                                 |
| `callbacks`             | The names in the `callbacks` map of an operation           | default                                                                                                                                                                 |
| `callback`              | Callback (its runtime expressions)                         | default                                                                                                                                                                 |
| `content`               | The media types of a `content` map                         | default                                                                                                                                                                 |
| `headers`               | The names of a `headers` map                               | default                                                                                                                                                                 |
| `properties`            | The names in `properties`, `patternProperties`, `$defs` and `dependentSchemas` | default                                                                                                                                     |
| `scopes`                | OAuth scopes                                               | default                                                                                                                                                                 |
| `extension`             | Everything inside the value of an `x-` field               | default                                                                                                                                                                 |
| `exampleValue`          | Everything inside example payloads, `default`, `const` and `enum` values | default                                                                                                                                       |

The keys of named maps and raw values are independent of the object keys: for
example, `componentNames: sorted` with `properties: original` and a fixed
`schema` order sorts the schemas of the components by name, keeps the
properties of each schema in their order and puts the keywords of each schema
in the fixed order. Arrays are never sorted.

**Example** - Sorted component names, everything else as in the input

```yaml
commands:
  format:
    openapi:
      property_order:
        componentNames: sorted
```

## OpenAPI versions and object recognition

The formatter recognizes the objects of OpenAPI 3.0, 3.1 and 3.2 by their
place in the document, from the root down, so names chosen by the author (paths,
component names, schema properties) are never mistaken for fields:

- Schemas are recognized at every depth: under `properties`,
  `patternProperties`, `additionalProperties`, `items` (a schema, or the array
  of schemas of 3.0), `prefixItems`, `allOf`, `anyOf`, `oneOf`, `not`, `if`,
  `then`, `else`, `$defs`, `dependentSchemas`, `contains`, `propertyNames`,
  `unevaluatedItems`, `unevaluatedProperties` and `contentSchema`, and under
  the `itemSchema` of a 3.2 media type. Boolean schemas are left as they are.
- Path items and operations are recognized in `paths`, `webhooks`, the
  `callbacks` of operations at any depth and in components, and so are 3.2
  `query` operations and `additionalOperations`.
- Headers, media types, encodings (also 3.2 `prefixEncoding` and
  `itemEncoding`) and examples are recognized wherever the specification allows
  them, including the content and examples of headers.
- Example payloads, `default`, `const` and `enum` values and the values of `x-`
  fields are data: they are never formatted as OpenAPI objects, and their keys
  follow the `exampleValue` and `extension` orders.

An object in a place that allows a Reference Object (a parameter, request body,
media type, response, header, example, link, callback, security scheme or path
item) follows the `reference` order when it has a `$ref` field. A path item is
a Reference Object only when it has no other fields than `$ref`, `summary` and
`description`: next to its operations, `$ref` is merged with them. A schema with
`$ref` is always a schema, because `$ref` is a schema keyword since 3.1; the
`schema` order of the `recommended` configuration puts `$ref` first.

A document that is valid YAML or JSON is formatted even when it is not a valid
OpenAPI document; values in unexpected places keep the default order.
