OpenAPI Specification Learning Guide

repository·main·Indexed 42 days ago

https://github.com/oai/learn.openapis.org

An educational resource and guide for HTTP-based API designers and writers to formalize their APIs using an OpenAPI Description (OAD). It covers best practices for design-first approaches, managing large APIs using the DRY principle, and understanding the differences between the OpenAPI Specification (OAS) and OpenAPI Descriptions.

Tokens
23.7K
Snippets
58
Records
102
Agent score
54%

What's inside OpenAPI

  1. Overview of the OpenAPI Specification learning path

    main

    This documentation provides a structured way to learn the OpenAPI Specification (OAS) by breaking down the complex specification into manageable, topic-based modules. Instead of reading the full specification at once, you can learn through specific building blocks of an OpenAPI Description (OAD).

    Key learning modules include:

    • Core Structure: JSON/YAML syntax, openapi versioning, and info objects.
    • Endpoints & Methods: paths, responses, and HTTP methods.
    • Data & Payloads: content, schema, parameters, and requestBody.
    • Reusability: Using components and $ref to reuse descriptions.
    • Documentation: Using summary, description, and example/examples.
    • Infrastructure: servers, securitySchemes, and security.
    • Advanced Features: callbacks, webhooks, links, and sequential media types.
  2. New features in OpenAPI 3.2

    main

    OpenAPI 3.2 introduces several advanced capabilities for modern API patterns:

    Advanced HTTP Method Support

    • QUERY method: Supports complex filtering that includes a request body.
    • Custom HTTP methods: Enabled via additionalOperations.
    • Enhanced parameter handling: Includes support for in: querystring.

    Sequential and Streaming Data

    Supports real-time and streaming data via:

    • Server-Sent Events (text/event-stream).
    • JSON streaming (application/jsonl, application/json-seq).
    • itemSchema: A new field used to describe the schema of individual items in a sequential data stream.

    Security Enhancements

    • OAuth2 Device Authorization: A flow designed for devices with limited input capabilities.
    • Metadata: Support for oauth2MetadataUrl.
    • Deprecation: Ability to mark security schemes as deprecated.

    Discriminator Improvements

    • Optional Values: The discriminator can now use an optional value.
    • Fallback Configuration: Use defaultMapping to provide a fallback schema when a payload does not match the defined discriminator mapping.

    Enhanced Documentation and Examples

    • Structured Examples: Use dataValue for the actual data and serializedValue for the serialized representation.
    • Server Identification: Use the name field in server objects.
    • Document Identity: Use the $self field for document identity.
  3. Understand Dynamic References in OAS 3.1

    main

    Dynamic referencing is a feature introduced in JSON Schema draft 2020-12 and is supported in OpenAPI Specification (OAS) 3.1 and later. It allows you to define a placeholder reference target that can be overridden during validation based on the path taken to reach that reference. This enables more flexible schema definitions that adapt to the context in which they are used.

    Common use cases include:

    • Implementing generic types (templatized types): Creating reusable structures like container data structures or payload envelopes where the inner type can vary.
    • Extending recursive schemas: Allowing the OAS schema to add OAS-specific keywords to the standard JSON Schema dialect.
  4. Understand the core concepts of OpenAPI (OAS) and OpenAPI Descriptions (OAD)

    main

    The OpenAPI Specification (OAS) is a vendor-neutral, machine-readable format used to describe remote APIs that communicate via HTTP or HTTP-like protocols (such as WebSockets or CoAP).

    A description written using the OAS is called an OpenAPI Description (OAD). This OAD acts as a Contract between the provider (the party offering the service) and the consumer (the party requesting the service).

    Key benefits of using an OAD include:

    • Automated Documentation Generation: Create human-readable reference guides directly from the machine-readable file to prevent documentation from falling out of sync.
    • Code Generation: Generate boilerplate code for both providers and consumers in various programming languages, ensuring the implementation matches the specification.
    • Automated Validation: Use the description to automatically verify that data passed to the API satisfies defined constraints.
    • Mock Servers: Use examples within the OAD to power auto-generated mock servers, allowing consumers to test against the API before the provider has even written the implementation code.
  5. Use `$schema` declarations for dialect disambiguation

    main

    OpenAPI 3.1 supports the $schema keyword within Schema Objects. This allows you to explicitly declare the JSON Schema dialect being used (e.g., for external schema files), preventing tools from having to infer the version from context.

    {
       "$schema": "http://json-schema.org/draft-07/schema#"
    }
  6. Update or remove primitive values directly

    main

    In Overlay 1.1.0, you can target primitive values (like strings) directly in your actions. Previously, you were required to update the entire parent object to change a primitive value.

    overlay: 1.1.0
    info:
      title: Targeted Overlay
      version: 1.0.0
    actions:
      - target: $.paths['/foo'].get.description
        update: This is the new description
      - target: $.paths['/bar'].get.description
        update: This is the updated description
  7. Understand the difference between reference resolution and reference removal

    main

    When working with OpenAPI Descriptions (OADs), there are two primary ways to handle $ref pointers:

    1. Reference Resolution: The tool identifies the target of the reference and performs any necessary modifications (e.g., handling fields adjacent to $ref). The tool maintains a connection between the reference source and the target. This approach treats the OAD as a graph, allowing for complex structures where multiple references point to the same object. Tools using this method can process all valid OADs.

    2. Reference Removal: The tool replaces the $ref with its target value, effectively deleting the reference pointer. This approach treats the OAD as a tree. Because the original URI/pointer is discarded, this method can only support OADs that form tree structures; it cannot handle circular references or multiple references to the same object without duplicating data or breaking the structure.

  8. Control parameter serialization with 'style' and 'explode'

    main

    The style field determines how a parameter is serialized into the request. The effect depends on the parameter's type (Primitive, Array, or Object).

    Common Styles

    • simple: Basic serialization.
    • form: Used for query or form-data parameters.
    • label: Uses dot notation.
    • matrix: Uses semicolon notation.

    Array and Object Serialization

    The explode boolean controls how elements or fields are separated:

    • explode: true: Each element/field is expanded into its own parameter (e.g., ids=1&ids=2).
    • explode: false: Elements/fields are collapsed into a single parameter (e.g., ids=1,2).

    OpenAPI 3.2 introduces style: cookie for more accurate cookie parameter descriptions.

    # OpenAPI 3.2 cookie example
    paths:
      /dashboard:
        get:
          parameters:
            - name: preferences
              in: cookie
              style: cookie
              schema:
                type: object
                properties:
                  theme: { type: string }
                  language: { type: string }
  9. Configure the Path Item Object

    main

    A Path Item Object describes the HTTP operations available on a specific path.

    • Operations: You define operations using HTTP method names as keys, such as get, put, or delete.
    • Common Properties: You can include properties like summary or description at the Path Item level to apply to all operations on that path.
    paths:
      /board:
        get:
          ...
        put:
          ...
  10. Define data structures with the Schema Object

    main

    The schema field within a Media Type Object uses a Schema Object to define the data type of the content. The type field is required and can be one of: number, string, boolean, array, or object.

    Common Schema Properties by Type:

    • string: Use minLength and maxLength to constrain length. Use enum to limit values to a specific set.
    • integer/number: Use minimum and maximum to define a range.
    • array: Requires an items field (which is itself a Schema Object) to define the type of elements. Use minItems and maxItems to constrain the array size.
    • object: Requires a properties field, which is a map of property names to their respective Schema Objects.
    # Example: Integer with range
    content:
      application/json:
        schema:
          type: integer
          minimum: 1
          maximum: 100
    
    # Example: String with enum
    content:
      application/json:
        schema:
          type: string
          enum:
          - Alice
          - Bob
          - Carl
    
    # Example: Array of integers
    content:
      application/json:
        schema:
          type: array
          minItems: 1
          maxItems: 10
          items:
            type: integer
    
    # Example: Object with properties
    content:
      application/json:
        schema:
          type: object
          properties:
            productName:
              type: string
            productPrice:
              type: number
  11. Implement Links to describe operation relationships

    main

    The Link Object in OpenAPI allows you to describe relationships between operations at design time. Instead of relying on consumers to parse URLs out of response payloads (like HATEOAS), you can explicitly define how a response from one operation relates to another operation using operationId or operationRef.

    Key features include:

    • Targeting: Links can point to an operation via an unqualified operationId (resolved locally) or an operationRef (using standard JSON Reference).
    • Runtime Expressions: You can use Runtime Expressions to bind design-time relationship definitions to actual runtime data. These expressions can reference parts of the request, response, headers, or parameters.
    • Parameter Mapping: You can map values from the current request/response to the parameters required by the target operation.
    • Scoped Servers: A Link can implement a specific Server object that applies only to that specific link.

    Links are defined as a property of a Response Object, meaning they are always qualified by a specific HTTP status code.

    /board/{row}/{column}:
      get:
        operationId: get-square
        responses:
          "200":
            description: "OK"
            content:
              application/json:
                schema:
                  $ref: "#/components/schemas/mark"
            links:
              markSquare:
                description: Operation to use if the mark value returned indicates the square is empty
                operationId: put-square
                parameters:
                  row: $request.path.row
                  column: $request.path.column
  12. Common use cases for OpenAPI Overlays

    main

    Overlays are used to inject or transform data in an OpenAPI description for various purposes without changing the base file. Common scenarios include:

    • Localization: Translating documentation into different languages.
    • Environment Configuration: Providing specific configuration for different deployment environments.
    • Separation of Concerns: Managing metadata like gateway configurations or SLA (Service Level Agreement) information separately.
    • Traits: Applying sets of configuration data (e.g., multiple parameters or headers) to targeted objects.
    • Defaults: Providing default responses or parameters when they are missing from the original description.
    • Conditional Application: Applying configuration data globally or based on specific filter conditions.