Skip to content

Generating Models from OpenAPI with Github Actions

What is OpenAPI?

OpenAPI Banner

OpenAPI specification files make it much easy for developers to communicate how to interact with an API in a standardized way. OpenAPI is used by many technology companies, including Microsoft, Google, and SalesForce1. OpenAPI files are either YAML or JSON files that define the endpoints and model the data for an HTTP API.

Below are a few snippets from an example definition:

POST Definition

This snippet defines a POST operation to create a new pet.

    post:
      description: Creates a new pet in the store. Duplicates are allowed
      operationId: addPet
      requestBody:
        description: Pet to add to the store
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/NewPet'

GET Definition with path parameter

This snippet defines a GET operation allowing the user to fetch a Pet by ID

  /pets/{id}:
    get:
      description: Returns a user based on a single ID, if the user does not have access to the pet
      operationId: find pet by id
      parameters:
        - name: id
          in: path
          description: ID of pet to fetch
          required: true
          schema:
            type: integer
            format: int64

Pet Schema

This snippet defines the shape of the 'Pet' object

components:
  schemas:
    Pet:
      allOf:
        - $ref: '#/components/schemas/NewPet'
        - type: object
          required:
          - id
          properties:
            id:
              type: integer
              format: int64

Autogeneration

Pet Store

Once created, the definition file can be used to generate various types of files. The example to the right shows a Swagger2 HTML visualization that many developers will be familiar with. The clean, minimal YAML is automatically transformed into attractive, hostable HTML documentation.

Various tools exist for these kinds of transformations, in this example, we will focus on the 'OpenAPI Generator' project. This is a Java tool that can be used to generate docs, API clients, and server stubs. This example will focus on API client generation.

In this case, instead of managing the Java package installation, it is simpler to use the NPM CLI provided to execute relevant commands. This can be installed by the following command:

npm install @openapitools/openapi-generator-cli -g

Alternatively, we can use the npx command to run the cli without worrying about the installation. We can now pass the path to our definition and the language we would like to generate to the CLI

npx @openapitools/openapi-generator-cli generate -g python -i /path/to/my/definition.yaml -o output

Warning

Article is incomplete. Check back soon!


Last update: January 23, 2023
Authors: Reed Sutliff