An OpenAPI spec is a contract, and most of its readers are machines. OpenAPI best practices describe how to write that contract so that code generators, gateways, and developer portals interpret it correctly. A code generator turns every operationId into a method name, and the gateway enforces the security schemes the spec declares. The developer portal builds its navigation from tags, while a diff tool reads the schemas to tell whether a change breaks consumers. A valid spec alone is not enough for any of these tools. Passing validation against the OpenAPI schema only shows that the document is well-formed and says little about its quality. Whether a generator can turn it into usable code is a separate question.

How much a practice matters depends on which tool relies on it. Stable operation IDs and precise schemas come first because a mistake there breaks generated clients and contract tests. Naming style, by contrast, matters mostly to developers working with the documentation. Day to day, it also matters whether a linter can check a practice or a human reviewer has to. Once dozens of teams write specs, the practices that stick are mostly the ones a linter enforces automatically.

Note

The twelve OpenAPI best practices in this guide cover document structure, operations, schemas, errors and security, and changes to the spec. For each practice, this guide names who depends on it, such as the code generator, the gateway, the developer portal, or developers. It also notes whether the check can be automated. All YAML examples follow OpenAPI 3.1 and show just the fields relevant to that practice.

The OpenAPI best practices checklist

The table summarizes all twelve practices. The last column shows whether a practice can be checked automatically, which determines whether it belongs in the CI pipeline or in human review.

#PracticeMatters toAutomated check
1Choose an OpenAPI version your toolchain supportsCode generator, gateway, developer portalPartially
2Define once under components and reference with $refCode generator, developer portalPartially
3Name resources in the consumer’s domain language with consistent casingDevelopers in the portal, generated clientsPartially
4Give every operation a unique, stable operationIdCode generatorYes
5Group operations with tags that follow business domainsDeveloper portal, code generatorPartially
6Write summaries and descriptions for consumersDevelopers in the portalPartially
7Constrain schemas as tightly as the contract allowsCode generator, contract testsPartially
8Add examples that validate against their schemaDeveloper portal, mock serverYes
9Model nullability and polymorphism explicitlyCode generatorPartially
10Standardize error responses as a shared componentClient error handlingYes
11Declare security schemes and scopes per operationGateway, clientYes
12Mark deprecations and check every change for breaking changesAll consumersYes

How should an OpenAPI document be structured?

Structuring an OpenAPI document starts with choosing an OpenAPI version that the generator, gateway, and portal all support. The next steps are to define reusable components under components and to name resources in the consumer’s domain language. All three decisions are expensive to change later because every generated client and every portal page builds on them.

1. Choose an OpenAPI version your toolchain supports

Larger organizations often run several OpenAPI versions side by side, from 3.0 to 3.2. Version 3.1 aligned the Schema Object with JSON Schema 2020-12, which changes how nullability is written and lets teams reuse existing JSON Schemas as is. Version 3.2 adds hierarchical tags, the QUERY method, and streaming, as OpenAPI 3.2 Explained shows. Even so, the choice of version depends mostly on what your tooling can process.

Before moving to a newer version, confirm that the code generator, gateway, and developer portal can all read it. A new feature is of little use if one of your tools can no longer process the spec correctly. The platform team decides which OpenAPI versions are allowed. A linter then flags any spec whose openapi field has a different value. If some of your specs still date from the Swagger era, OpenAPI vs Swagger explains how the two relate.

2. Define once under components and reference with $ref

Anything that appears in more than one operation belongs under components and is pulled in with $ref. That applies to schemas, parameters, and responses alike. The generator then produces exactly one Order class for all operations, and a change to the schema takes effect everywhere at once. Inline schemas are fine for structures that occur exactly once, such as a small request body for a single action.

yaml
paths:
  /orders/{orderId}:
    get:
      operationId: getOrder
      tags: [Orders]
      parameters:
        - $ref: '#/components/parameters/OrderId'
      responses:
        '200':
          description: The order with all line items.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Order'
        '404':
          $ref: '#/components/responses/NotFound'
components:
  parameters:
    OrderId:
      name: orderId
      in: path
      required: true
      schema:
        type: string
        format: uuid

A linter can flag inline object schemas in responses. A reviewer has to decide whether two similar structures describe the same business concept.

3. Name resources in the consumer’s domain language with consistent casing

Names in a spec should come from the consumer’s domain language. That goes for paths, parameters, and properties alike. A path like /customers/{customerId}/contracts tells a partner’s developer far more than /kd_stamm/{id}/vtr, which mirrors a database table. A style guide should also set one case convention per element type, such as kebab-case for path segments and camelCase for properties and parameters.

Mixed casing ends up in every generated client. Once the first consumer is live, it is hard to correct because every rename is then a breaking change. A linter checks casing reliably. Only a reviewer can tell whether a name comes from the domain language or from an internal system.

What makes operations easy to generate and document?

An operation is easy to generate and document when it has a stable operationId, a domain tag, and a meaningful description. The generator needs the operationId for the method name, the portal needs the tag for navigation, and developers need the description to integrate the API.

4. Give every operation a unique, stable operationId

In generated SDKs, the operationId becomes the method name, for example ordersApi.getOrder(). If it is missing, generators derive the name from path and method, which produces names like ordersOrderIdGet. If it changes, consumer code stops compiling the next time the client is regenerated, even though the HTTP contract has not changed.

That makes the operationId part of the contract, even though it never appears in an HTTP request. The specification already requires it to be unique across all operations in the API. Teams should also agree on a naming pattern, usually verb plus noun in camelCase, and change an existing ID only in a new major version. The linter checks uniqueness and pattern on every PR, and the spec diff described in practice 12 catches a rename.

5. Group operations with tags that follow business domains

Tags drive the navigation in the developer portal, and many generators create one client class per tag. With domain-based tags such as Orders, Payments, or Customers, the portal and the generated client mirror the structure consumers already know. Tags named after teams or microservices mirror the org chart, and the org chart usually changes faster than the business domain.

Declare each tag at the top level with a description, and give each operation exactly one tag so that it appears in one place in the portal. For large APIs, OpenAPI 3.2 adds the parent field for nested tags. A linter checks that every tag is declared and described. A reviewer still has to confirm that the tag structure fits the business domain.

6. Write summaries and descriptions for consumers

The summary appears in the portal navigation, so keep it to one line. The description covers what the path cannot express, such as behavior, side effects, idempotency, preconditions, and limits. A description like "Returns an order" only repeats what GET /orders/{orderId} already says. A description like "Returns the order with all line items, including canceled orders" tells the reader something the path does not.

Descriptions support CommonMark, so you can include short lists and links to guides. A linter checks that both fields are present and meet a minimum length. It takes a reviewer to judge whether the text actually helps a consumer.

How precise should OpenAPI schemas be?

A schema should contain exactly the constraints the API provider can guarantee over time. Consumers can rely on every constraint, and contract tests verify the implementation against it. Where a constraint is missing, each consumer makes its own assumption.

7. Constrain schemas as tightly as the contract allows

OpenAPI has a dedicated keyword for the common constraints. Required fields go in required, while format marks dates, UUIDs, and email addresses. Fixed sets of values use enum, and where the backend already enforces a limit, maxLength or maximum documents it. The following schema for an order uses these constraints and includes an example at the schema level.

yaml
components:
  schemas:
    Order:
      type: object
      required: [id, status, createdAt, items]
      properties:
        id:
          type: string
          format: uuid
        status:
          type: string
          enum: [pending, confirmed, shipped, cancelled]
        createdAt:
          type: string
          format: date-time
        note:
          type: [string, 'null']
          maxLength: 500
        items:
          type: array
          minItems: 1
          maxItems: 200
          items:
            $ref: '#/components/schemas/OrderItem'
      examples:
        - id: 7f3c2a9e-5b1d-4c8e-9f20-3a6b8d1e4c57
          status: confirmed
          createdAt: '2026-11-18T09:30:00Z'
          note: null
          items:
            - sku: AP-1001
              quantity: 2
    OrderItem:
      type: object
      required: [sku, quantity]
      properties:
        sku:
          type: string
          maxLength: 40
        quantity:
          type: integer
          minimum: 1

The additionalProperties keyword calls for a conscious choice. Set to false in a request schema, it lets the gateway catch misspelled fields early. In a response schema, the same setting turns every new field into a breaking change for clients that validate strictly. That is why many teams close request schemas and leave response schemas open. Enums in responses carry a similar risk because a new value breaks any client that only handles the known values. The style guide should say whether consumers must tolerate unknown values.

A linter can require required, format, and length limits for strings. Choosing limits that make sense for the business still takes a reviewer.

8. Add examples that validate against their schema

Examples are used directly in three places. The portal displays them, mock servers return them, and try-it consoles prefill requests with them. When an example contradicts its schema, consumers inherit the mistake because they tend to copy examples before they read schemas. In OpenAPI 3.1, examples in the Schema Object is an array, as the Order schema in practice 7 shows. At the media type level, named examples with a summary cover additional cases, such as a canceled order.

A linter can verify that every example matches its schema, and that check belongs in CI. The rule is cheap to run in the linter, and reviewers no longer have to check examples against the schema by hand.

9. Model nullability and polymorphism explicitly

Optional and nullable mean different things. An optional field can be absent from the payload, while a nullable field can hold null as well as a value of its declared type. In OpenAPI 3.1, nullability is part of the type, as type: [string, 'null'] on the note field of the Order schema in practice 7 shows. The nullable: true keyword from 3.0 no longer has any effect in 3.1. It often survives a migration anyway because validators ignore it as an unknown keyword. The field is then no longer nullable, and a client that validates strictly rejects null.

For polymorphic payloads, oneOf combined with a discriminator lets generators produce real subtypes. Without a discriminator, many generators fall back to a generic object or a map, and the consumer has to work out the type at runtime.

yaml
components:
  schemas:
    PaymentMethod:
      oneOf:
        - $ref: '#/components/schemas/CardPayment'
        - $ref: '#/components/schemas/SepaPayment'
      discriminator:
        propertyName: type
        mapping:
          card: '#/components/schemas/CardPayment'
          sepa: '#/components/schemas/SepaPayment'
    CardPayment:
      type: object
      required: [type, last4]
      properties:
        type:
          const: card
        last4:
          type: string
          pattern: '^[0-9]{4}$'
    SepaPayment:
      type: object
      required: [type, iban]
      properties:
        type:
          const: sepa
        iban:
          type: string
          maxLength: 34

A linter finds nullable in 3.1 documents and oneOf without a discriminator. The team decides during API design whether a payload should be polymorphic at all.

How should errors and security be described?

Errors and security belong in shared components that every operation references. As a result, the gateway, the generated client, and the documentation in the portal treat errors and permissions the same way for every operation.

10. Standardize error responses as a shared component

RFC 9457 (Problem Details for HTTP APIs) defines a common error format with the fields type, title, status, detail, and instance and the media type application/problem+json. When every operation references this format, each consumer needs just one error handler. All it takes is one shared schema and one response component for each common status code. Validation errors can extend the format with a list of the affected fields.

yaml
components:
  schemas:
    Problem:
      type: object
      required: [type, title, status]
      properties:
        type:
          type: string
          format: uri-reference
        title:
          type: string
        status:
          type: integer
          minimum: 400
          maximum: 599
        detail:
          type: string
        instance:
          type: string
          format: uri-reference
  responses:
    NotFound:
      description: The resource does not exist or is not visible to the caller.
      content:
        application/problem+json:
          schema:
            $ref: '#/components/schemas/Problem'

A linter checks that every operation declares its 4xx responses and that they reference the shared schema.

11. Declare security schemes and scopes per operation

Security schemes are defined once under components. The top-level security field uses them to set a default for all operations, which individual operations override with their own scopes. The scope on the operation tells the gateway what to enforce and tells the consumer which permission to request. Public endpoints should set security: [] explicitly so that a reviewer can tell an intentionally open endpoint from a forgotten one.

yaml
security:
  - oauth: [orders:read]
paths:
  /orders:
    post:
      operationId: createOrder
      tags: [Orders]
      security:
        - oauth: [orders:write]
      responses:
        '201':
          description: The order was created.
  /health:
    get:
      operationId: getHealth
      tags: [Operations]
      security: []
      responses:
        '200':
          description: The service is available.
components:
  securitySchemes:
    oauth:
      type: oauth2
      flows:
        clientCredentials:
          tokenUrl: https://auth.example.com/oauth2/token
          scopes:
            orders: read: Read orders
            orders: write: Create and change orders

The linter checks that every operation is covered by a scheme and that write operations require a write scope.

How do you change a spec without breaking consumers?

You can change a spec safely when the team deprecates elements well before removing them and CI diffs every change against the last published version. Most breaking changes are accidental, such as a renamed property, a new required request field, or a narrowed enum. A spec diff in CI catches them before release.

12. Mark deprecations and check every change for breaking changes

You can set deprecated on operations, parameters, and schema properties. Portals display it, and generators carry it into the code. Consumers then see the deprecation warning in their IDE. The description should say when the element will be removed and what replaces it. At runtime, the Deprecation header from RFC 9745 signals when the deprecation takes effect, and the Sunset header from RFC 8594 announces the date the endpoint is retired.

yaml
paths:
  /orders/{orderId}/cancel:
    post:
      operationId: cancelOrder
      tags: [Orders]
      deprecated: true
      description: >-
        Deprecated since version 2.4.0 and scheduled for removal on
        2027-06-30. Use PATCH /orders/{orderId} with status cancelled.
      parameters:
        - $ref: '#/components/parameters/OrderId'
      responses:
        '204':
          description: The order was cancelled.

The spec diff in CI checks for breaking changes. It blocks the merge when it finds one and the major version is unchanged. Removing an operation counts too, so mark it as deprecated first and remove it in the next major version. For how info.version relates to these changes, see API Versioning Strategy. In API Portal, the Version Diff shows the differences between two API versions side by side.

Which practices can a linter check, and which need review?

The linter and the spec diff cover five of the twelve practices almost completely and the structural part of the other seven. Those five cover operation IDs, examples, error responses, security, and breaking changes. All of these checks run in CI and add almost no time once they are set up.

That leaves reviewers with the domain questions no linter can answer. The reviewer decides whether a name comes from the domain language and whether a description helps a consumer. The reviewer also judges whether the limits in a schema are right for the business and whether the tag structure fits the business domain. Manual Review vs. Automated Linting goes deeper into how the linter and human review divide the work. OpenAPI Linting covers linter rule categories and how severity levels drive a quality gate.

Who owns the OpenAPI style guide?

A style guide needs an owner who maintains the ruleset and decides on exceptions. That role usually falls to the platform team or the API governance function. Teams request a change or an exception through a PR against the ruleset. Every decision then lives in the same repository as the rules, with a clear audit trail.

Introduce new rules as warnings so that teams see the findings before those rules start failing builds. After a few weeks, they become errors for new and changed specs, while existing specs are baselined and brought into compliance at their next change. That way no older API is blocked overnight, and the ruleset still applies to everything that changes. To see how the style guide fits into the wider governance model, read What Is API Governance?.

Start applying OpenAPI best practices

Start by linting all existing specs to establish a baseline. It shows where your existing specs stand and which findings occur most often. A good starting set is the five practices a linter and a spec diff can check on their own. These are unique operation IDs, shared error responses, security per operation, valid examples, and the check for breaking changes. They start as warnings for new and changed specs and become errors after a few weeks, and the ruleset grows from there.

API Linter
Enforce your OpenAPI style guide in every PR
150+ rules out of the box, configurable and extensible with custom rules, with findings directly in the merge request.
Explore the API Linter

Frequently asked questions about OpenAPI best practices

The specification has carried the OpenAPI name since it moved to the OpenAPI Initiative, and 3.0 was the first major version released under it. Swagger refers to the 2.0 format and earlier, and to the tools SmartBear still publishes under that name. For the full difference, see OpenAPI vs Swagger.

What matters is whether your generator, gateway, and portal support the version. Version 3.1 brings full compatibility with JSON Schema. Version 3.2 adds hierarchical tags, the QUERY method, and streaming. If your entire API toolchain reads 3.2, new APIs can start there. Otherwise, 3.1 is the safer target.

Fewer than most teams write down at first. A few rules that block the merge achieve more than a long list of warnings nobody reads. Teams usually start with five to ten blocking rules and add more once the existing specs comply with the first ones.

Yes. A spec generated from annotations feeds the same generators, gateways, and portals as a handwritten one. The only difference is where you fix findings, which is in the code annotations. Linting the generated spec in CI catches the problems either way, and Spec-First API Development compares the two approaches.