DEV Community

Cover image for How to Write an OpenAPI Description
Skip Everling
Skip Everling

Posted on

How to Write an OpenAPI Description

There’s a lot you can do once you have an API description file formatted according to the OpenAPI Specification (or its predecessor spec, Swagger). Using a standardized API description format as a single source of truth allows for better API design & development, as well as the automatic generation and deployment of API reference documentation.

Since API descriptions are plain text format, you can use any text editor to create one. It can be helpful to begin with a template so you don’t have to start from scratch (below there's one you can copy!). Alternatively, if the API you want to document is already in production, we'll explore some other options to generate an API description file.

If you need a review of what OpenAPI and Swagger are, check out ReadMe: How to Use OpenAPI and Swagger for Documentation

OpenAPI-Swagger-spec

OpenAPI Template

To get started with an OpenAPI file, it can be helpful to start with a basic outline that includes the essential syntax. Then you can step through each line and make edits to include the proper details from your API.

You don’t have to start from scratch! Here is a template OpenAPI definition:

openapi: "3.0.0"
info:
  version: 1.0.0 // Version of your API
  title: Your API Title
  description: An API description template
  contact:
    name: Your Name
    email: email@example.com
    url: http://example.com
  license:
    name: License Name
    url: http://example.com/license-url
servers:
  - url: http://api.example.com
paths:
  /your_endpoint:
    get:
      description: |
        Multi-line description
        of your API endpoint
      operationId: yourOperation
      parameters:
        - name: your_param
          in: query
          description: Description of your param
          required: false
          schema:
            type: string
      responses:
        '200':
          description: Your success description

This template doesn’t include complete coverage of all possible OpenAPI fields, but it’s useful as starter code. In most cases you’ll want to add your own response schemas and reusable components. You can dig into the OAS specification itself or see our OpenAPI and Swagger examples below.

Once you have an initial framework for your API described, you can complete coverage for the remainder of your API.

OpenAPI Descriptions are Written in JSON or YAML

When you write your OpenAPI or Swagger file, you can choose from either of two formats: JSON or YAML. Both will use the same data structure (determined by the Swagger or OpenAPI specification), but each will have a different syntax representation. JSON may look familiar to most web developers and it is the most common format used to return actual API results. YAML may also look familiar, as it’s often used in configuration files.

YAML uses whitespace and minimal markup, which can make it more human-readable compared to JSON.

Below is an example OpenAPI 3 YAML description, showing the header and one path/response.

openapi: "3.0.0"
info:
  version: 1.0.0
  title: Swagger Petstore
  license:
    name: MIT
servers:
  - url: http://petstore.swagger.io/v1
paths:
  /pets:
    get:
      summary: List all pets
      operationId: listPets
      tags:
        - pets
      parameters:
        - name: limit
          in: query
          description: How many items to return at one time (max 100)
          required: false
          schema:
            type: integer
            format: int32
      responses:
        '200':
          description: A paged array of pets
          headers:
            x-next:
              description: A link to the next page of responses
              schema:
                type: string
          content:
            application/json:    
              schema:
                $ref: "#/components/schemas/Pets"

OAS Examples, Petstore YAML

**JSON **is the more common format for data exchange, but is less human-readable. Here’s the same OpenAPI 3 description fomatted using JSON:

{
   "openapi": "3.0.0",
   "info": {
      "version": "1.0.0",
      "title": "Swagger Petstore",
      "license": {
         "name": "MIT"
      }
   },
   "servers": [
      {
         "url": "http://petstore.swagger.io/v1"
      }
   ],
   "paths": {
      "/pets": {
         "get": {
            "summary": "List all pets",
            "operationId": "listPets",
            "tags": [
               "pets"
            ],
            "parameters": [
               {
                  "name": "limit",
                  "in": "query",
                  "description": "How many items to return at one time (max 100)",
                  "required": false,
                  "schema": {
                     "type": "integer",
                     "format": "int32"
                  }
               }
            ],
            "responses": {
               "200": {
                  "description": "A paged array of pets",
                  "headers": {
                     "x-next": {
                        "description": "A link to the next page of responses",
                        "schema": {
                           "type": "string"
                        }
                     }
                  },
                  "content": {
                     "application/json": {
                        "schema": {
                           "$ref": "#/components/schemas/Pets"
                        }
                     }
                  }
               }
            }
         }
      }
   }
}

OAS Examples, Petstore JSON

Modern programming languages and their respective web frameworks can readily consume JSON objects, and this is a major reason for why many API providers adopt the JSON format. Most web developers are familiar with JSON syntax thanks to its resemblance to Javascript.

Neither YAML or JSON are immune to human error, but editors with linters will catch the most common errors.

You can convert files between JSON and YAML, so feel free to choose whichever format is preferable for you and your team.

How to Write OpenAPI Descriptions With Your Favorite Code Editor

Your current development environment or text editor will include YAML and JSON syntax highlighting and may already include Swagger and OpenAPI syntax support as well. Look for plugins, which can help with syntax suggestions or checking for errors as you write your API description. Alternatively, you can use existing open source or web-based tools.

For example, the VSCode editor has an open source linter plugin to check YAML and JSON files against Swagger and OpenAPI specifications.

Code Linter

Shown above is an example of an in-editor linter program which will raise errors and flag conventions for cleaner code. You can click each error to go to the line where the issue originated. In the screenshot, we accidentally misspelled description, resulting in the linter raising missing required property errors on line 48 with the typo.

With most editors, you can edit either OpenAPI or Swagger files in YAML, with syntax help and built-in linting. When finished, you can programmatically convert YAML to the equivalent JSON.

How to Generate OpenAPI Descriptions From an Existing API

If you already have an API in production, you can benefit from documenting it in an OpenAPI file. To save yourself some time, look for some ways you can generate the descriptions from your code or live traffic.

If your API is built in a common framework, such as Falcon (Python) or Rails (Ruby), your code already has everything needed to create a Swagger or OpenAPI description. Look for an existing project that creates an API definition based on an existing API. For example, zero-rails_openapi gem is a Rails solution and falcon-apispec does the same for Falcon. You can also create API descriptions from code comments.

There could be many reasons it's not possible to reference source code. In that case, you might use a service like Optic to listen to live API traffic. After reviewing live requests and responses, Optic can output an OpenAPI or Swagger file.

Finally, another option is to make small updates to comments in your code. Using the oas Node module, you can generate your definition from inline YAML. This is a ReadMe open source tool where it is used internally to document APIs from code.

Hope this helps you to create and make use of an OpenAPI description for your API!

This is an excerpt from my extended guide on ReadMe: How to Use OpenAPI and Swagger for Documentation

Top comments (0)