Let me introduce you to OpenAPI

By Maarten Van Hoof

5 min read

OpenAPI allows us to improve effeciency between teams and interdependent projects. It allows us to describe our API in a single document. In this part of the series, we will take you through the most important parts of an OpenAPI document.

Authors

In the previous part of this series, we introduced you to the purpose of contracts between API providers and consumers. This visibility allows us to improve efficiency between teams and interdependent projects, wether that be internal or external projects.

Let us walk you through a few sections of an OpenAPI document, the ones that will most likely the largest part of your document and where most of the information is stored.

Main sections

OpenAPI files can be written in both JSON and YAML format. For brevity, we will use the YAML format.

# Specification version
openapi: ...

# General API metadata
info: ...

# Server information. BaseURLs, environments, ...
servers: ...

# Available paths & operations
paths: ...

# Datamodel abstraction
components: ...

# Security mechanisms can be used across the API
security: ...

# Grouping of paths & components
tags: ...

# Additional external documentation
external docs: ...

# Webhook operations, similar to paths, only API is now a consumer.
webhooks: ...

On the first level, we describe a few general sections and properties. First, we need to declare our OpenAPI version. This is to ensure compatibility with certain types of tooling.

Next, we can declare some general information with the info property. Who has written this document, where to contact the authors, etc.

In the servers section, we can declare multiple base URLs on which the API will be available. For instance, when you have various environments available.

The first major section of a typical OpenAPI document is the paths section. Here we describe our operations, which are a combination of paths and HTTP methods. These operations describe the required data that the consumer has or can provide, like query string parameters, URL parameters, request bodies and the data that the API can respond with, status codes, content types, and data formats.

The second major section is the components section. The OpenAPI specification extends the JSON schema specification. It allows us to reuse parts of our internal and external documents with the power of JSON schema references. In the components section, we can abstract and define data models that we can refer to from our operations.

We define the security mechanisms to which our API validates the consumer in the security section, and link each mechanism to the operations needing a specific mechanism.

In the tags section, we can add taxonomy to group our operations, provide links to external documentation and declare webhooks where the API now becomes a consumer itself.

Furthermore, we can add external documentation to our API if the format of this document does not suffice your needs, and we can declare webhooks where the API now becomes a consumer itself.

Paths

paths:
  /pets:
    get:
      summary: List all pets
      #...
    post:
      summary: Create a pet
      #...

  /pets/{petId}:
    get:
      summary: Info for a specific pet
      #...

In paths, we first declare the URL the operation is available on, next the HTTP method. The combination of a URL and an HTTP method is called an operation in the OpenAPI context.

Operations

paths:
  /pets:
    get:
      # A unique identifier for this operation. Mostly used in OpenAPI tooling.
      operationId: listPets
      # A short summary of what the operation does
      summary: List all pets
      # A list of tags for API documentation control. Tags can be used for logical grouping of operations by resources or any other qualifier.
      tags:
        - pets
      parameters:
        - name: limit
          # It is a query string parameter
          in: query
          # A more thorough description of what this parameter does to a request
          description: Limit how many pets this API will return.
          # It is not required
          required: false
          # It must be an 32-bit integer
          schema:
            type: integer
            format: int32

      # description
      # requestBody
      # security
      # ...

      responses:
        #...

In an operation, we can declare the parameters or requestBody it should or can receive and how it should respond. We can also declare an operationId, which most tooling uses as an identifier for other functionalities, a summary or description to better describe the functionality this operation offers, which security schemes this operation has to adhere to, etc.

Responses

paths:
  /pets:
    get:
      #...

      responses:
        '200':
          description: Expected response to a valid request
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Pets'
        default:
          description: unexpected error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'

We declare an operation response by stating a status code or the keyword default for a default response an operation should return when the defined status codes don't suffice. Very handy to declare a default error response that produces the same error format for all erroneous status codes.

Then we declare the Content-Type with which the provider will respond. RESTful APIs aren't limited by responding only in JSON. XML, plain text, HTML, and also binaries are possible Content-Types one can define.

Next, we'll define the data model with which our API provider will respond. This can be the entire definition of a component at once or a reference to a component defined in the root-level section Components.

The OpenAPI specification extends the JSON schema specification and allows us to use one of its powerful features: References. With references, we can refer to other parts of the document or refer to parts of external documents. References are declared with the $ref keyword.

I'll explain more about the declaration of data models in the next section, but for now, we'll just use a reference to a component.

Components

In the components object, we can describe data models we can reuse throughout our document thanks to JSON schema references' power with the $ref keyword. More information about the $ref keyword can be found here. It allows us to keep our OpenAPI document a bit cleaner, with less repetition and more DRY.

components:
  schemas:
    Pet:
    Pets:

  responses:
    ErrorResponse:

  requestBodies:
    NewPet:

  headers:
    Limit:
    Offset:
    Pagination:

The Components object has several fixed fields to subcategorise the type of component we declare.

  • schemas: Input and output data types.
  • responses: Response objects
  • parameters: Operation parameters; path, query-string, ...
  • examples: Example objects that can describe more realistic data
  • requestBodies: RequestBody objects
  • headers: Header objects
  • securitySchemes: securitySchemes Objects ...

Schemas

In the schema object, we describe a document's most atomic level of data objects: our responses' input and output types, requestBodies, parameters, etc.

components:
  schemas:
    Pet:
      type: object
      properties:
        id:
          type: integer
          format: int64
        name:
          type: string
        image:
          type: string
        tag:
          type: string
      required:
        - id
        - name

    Pets:
      type: array
      items:
        $ref: '#/components/schemas/Pet'

For example, we describe our Pet as an object. It has the properties id, name, image, and tag. All, except id, are described as values of the type string. Id is defined as a 64-bit integer. Id and name are described as required, meaning API consumers should consider that the image and tag value could not be in the returned data. We can reuse our Pet component to create a Pets component, an array of the Pet component.

Conclusion

In this article, we've seen how to define an OpenAPI document. We've seen how to define the metadata of our API, the operations it offers, the responses it can return, and how to define and reuse the data models it uses.

In the next part of this series, we'll show you ways of integrating OpenAPI in to your team and project workflows.


Upcoming events

  • Coven of Wisdom - Herentals - Winter `24 edition

    Worstelen jij en je team met automated testing en performance? Kom naar onze meetup waar ervaren sprekers hun inzichten en ervaringen delen over het bouwen van robuuste en efficiรซnte applicaties. Schrijf je in voor een avond vol kennis, heerlijk eten en een mix van creativiteit en technologie! ๐Ÿš€ 18:00 โ€“ ๐Ÿšช Deuren open 18:15 โ€“ ๐Ÿ• Food & drinks 19:00 โ€“ ๐Ÿ“ข Talk 1 20:00 โ€“ ๐Ÿน Kleine pauze 20:15 โ€“ ๐Ÿ“ข Talk 2 21:00 โ€“ ๐Ÿ™‹โ€โ™€๏ธ Drinks 22:00 โ€“ ๐Ÿป Tot de volgende keer? Tijdens deze meetup gaan we dieper in op automated testing en performance. Onze sprekers delen heel wat praktische inzichten en ervaringen. Ze vertellen je hoe je effectieve geautomatiseerde tests kunt schrijven en onderhouden, en hoe je de prestaties van je applicatie kunt optimaliseren. Houd onze updates in de gaten voor meer informatie over de sprekers en hun specifieke onderwerpen. Over iO Wij zijn iO: een groeiend team van experts die end-to-end-diensten aanbieden voor communicatie en digitale transformatie. We denken groot en werken lokaal. Aan strategie, creatie, content, marketing en technologie. In nauwe samenwerking met onze klanten om hun merken te versterken, hun digitale systemen te verbeteren en hun toekomstbestendige groei veilig te stellen. We helpen klanten niet alleen hun zakelijke doelen te bereiken. Samen verkennen en benutten we de eindeloze mogelijkheden die markten in constante verandering bieden. De springplank voor die visie is talent. Onze campus is onze broedplaats voor innovatie, die een omgeving creรซert die talent de ruimte en stimulans geeft die het nodig heeft om te ontkiemen, te ontwikkelen en te floreren. Want werken aan de infinite opportunities van morgen, dat doen we vandaag.

    | Coven of Wisdom Herentals

    Go to page for Coven of Wisdom - Herentals - Winter `24 edition
  • Mastering Event-Driven Design

    PLEASE RSVP SO THAT WE KNOW HOW MUCH FOOD WE WILL NEED Are you and your team struggling with event-driven microservices? Join us for a meetup with Mehmet Akif Tรผtรผncรผ, a senior software engineer, who has given multiple great talks so far and Allard Buijze founder of CTO and founder of AxonIQ, who built the fundaments of the Axon Framework. RSVP for an evening of learning, delicious food, and the fusion of creativity and tech! ๐Ÿš€ 18:00 โ€“ ๐Ÿšช Doors open to the public 18:15 โ€“ ๐Ÿ• Letโ€™s eat 19:00 โ€“ ๐Ÿ“ข Getting Your Axe On Event Sourcing with Axon Framework 20:00 โ€“ ๐Ÿน Small break 20:15 โ€“ ๐Ÿ“ข Event-Driven Microservices - Beyond the Fairy Tale 21:00 โ€“ ๐Ÿ™‹โ€โ™€๏ธ drinks 22:00 โ€“ ๐Ÿป See you next time? Details: Getting Your Axe On - Event Sourcing with Axon Framework In this presentation, we will explore the basics of event-driven architecture using Axon Framework. We'll start by explaining key concepts such as Event Sourcing and Command Query Responsibility Segregation (CQRS), and how they can improve the scalability and maintainability of modern applications. You will learn what Axon Framework is, how it simplifies implementing these patterns, and see hands-on examples of setting up a project with Axon Framework and Spring Boot. Whether you are new to these concepts or looking to understand them more, this session will provide practical insights and tools to help you build resilient and efficient applications. Event-Driven Microservices - Beyond the Fairy Tale Our applications need to be faster, better, bigger, smarter, and more enjoyable to meet our demanding end-users needs. In recent years, the way we build, run, and operate our software has changed significantly. We use scalable platforms to deploy and manage our applications. Instead of big monolithic deployment applications, we now deploy small, functionally consistent components as microservices. Problem. Solved. Right? Unfortunately, for most of us, microservices, and especially their event-driven variants, do not deliver on the beautiful, fairy-tale-like promises that surround them.In this session, Allard will share a different take on microservices. We will see that not much has changed in how we build software, which is why so many โ€œmicroservices projectsโ€ fail nowadays. What lessons can we learn from concepts like DDD, CQRS, and Event Sourcing to help manage the complexity of our systems? He will also show how message-driven communication allows us to focus on finding the boundaries of functionally cohesive components, which we can evolve into microservices should the need arise.

    | Coven of Wisdom - Utrecht

    Go to page for Mastering Event-Driven Design
  • The Leadership Meetup

    PLEASE RSVP SO THAT WE KNOW HOW MUCH FOOD WE WILL NEED What distinguishes a software developer from a software team lead? As a team leader, you are responsible for people, their performance, and motivation. Your output is the output of your team. Whether you are a front-end or back-end developer, or any other discipline that wants to grow into the role of a tech lead, RSVP for an evening of learning, delicious food, and the fusion of leadership and tech! ๐Ÿš€ 18:00 โ€“ ๐Ÿšช Doors open to the public 18:15 โ€“ ๐Ÿ• Letโ€™s eat 19:00 โ€“ ๐Ÿ“ข First round of Talks 19:45 โ€“ ๐Ÿน Small break 20:00 โ€“ ๐Ÿ“ข Second round of Talks 20:45 โ€“ ๐Ÿ™‹โ€โ™€๏ธ drinks 21:00 โ€“ ๐Ÿป See you next time? First Round of Talks: Pixel Perfect and Perfectly Insane: About That Time My Brain Just Switched Off Remy Parzinski, Design System Lead at Logius Learn from Remy how you can care for yourself because we all need to. Second Round of Talks: Becoming a LeadDev at your client; How to Fail at Large (or How to Do Slightly Better) Arno Koehler Engineering Manager @ iO What are the things that will help you become a lead engineer? Building Team Culture (Tales of trust and positivity) Michel Blankenstein Engineering Manager @ iO & Head of Technology @ Zorggenoot How do you create a culture at your company or team? RSVP now to secure your spot, and let's explore the fascinating world of design systems together!

    | Coven of Wisdom - Amsterdam

    Go to page for The Leadership Meetup

Share