YAML anchors & aliases

Hey! Last week I was focused on moving the API specification from slatedocs to OpenAPI. This was the first that I had the pleasure of writing a schema by hand, before that I always generated it. I learned a lot and I would like to share one thing.

By default the OpenAPI allows you to define a schema for reusability. But there is one more thing that you can do for reusability – YAML anchors and aliases. By using it you can reuse much more than just a schema:

paths:
  /orders:
    post:
      responses:
        201: &submission-response-accepted
          description: Order has been accepted for production
          content:
            application/json:
              schema:
                # not important
        409: &submission-response-duplicate
          description: Order is a duplicate and it has been rejected
          content:
            application/json:
              schema:
                # not important
        422:
          description: Order has been rejected
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SubmissionErrors'
              examples:
                Invalid `address_to` and `shipping`: &submission-response-rejected-address-to-and-shipping
                  value:
                    # not important
                Invalid `package_inserts`: &submission-response-rejected-package-inserts
                  value:
                    # not important
                SKU is out of stock: &submission-response-rejected-oos
                  value:
                    # not important

  /facilities/{facility_id}/orders.json:
    post:
      responses:
        201: *submission-response-accepted
        404:
          description: Facility not found
          content:
            application/json:
              schema:
                # not important
        409: *submission-response-duplicate
        422:
          description: Order has been rejected
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/FacilitySubmissionErrors'
              examples:
                address_to_and_shipping: *submission-response-rejected-address-to-and-shipping
                package_inserts: *submission-response-rejected-package-inserts
                out_of_stock: *submission-response-rejected-oos

First, you have to define a part of the code that you would like to reuse via the & sign – an anchor.

Next, in order to reuse it, you have to use an alias via * sign. This way the code will be reused!

Have a great week!