The first thing to know is that an OpenAPI specification must be a valid JSON document. The specification also explicitly allows YAML, which is a superset of JSON and can be converted to JSON. We will be using YAML because it is more readable (and thus writable) by humans, even for non-developers. Furthermore, you can add comments inside YAML files, something that's not possible with JSON.
Let's start by learning the basics of YAML. We only need to learn a few basic pieces of syntax to write our OpenAPI specification.
Like JSON, getting started with the basic syntax for YAML is very simple. All YAML documents start with three dashes (---) to indicate the start of the file, and three periods (...) to indicate the end of the file.
Typically, the most common data structures you need to represent in a configuration file are key-value pairs and lists. To represent a set of key-value pairs, simply write each one on a new line, separated by a colon and space:
# YAML
title: Hobnob
description: Simple publishing platform
# JSON
{
"title": "Hobnob",
"description": "Simple publishing platform"
}
To represent nested objects, simply indent the child object by two spaces:
# YAML
info:
title: Hobnob
description: Professional publishing platform
# JSON
{
"info": {
"title": "Hobnob",
"description": "Professional publishing platform"
}
}
To represent a list, place each item on a new line, preceded by a dash and a space:
# YAML
produces:
- application/json
- text/html
# JSON
{
"produces": [
"application/json",
"text/html"
]
}
To conserve newline characters, use the pipe (|) character:
# YAML
info:
title: Hobnob
description: |
The professional user directory.
Find like-mind professionals on Hobnob!
# JSON
{
"info": {
"title": "Hobnob",
"description": "The professional user directory.\n\nFind like-mind professionals on Hobnob!\n"
}
}
Or to break a line of text over multiple lines (to make it easier to read), which shouldn't preserve newlines, use the greater-than character (>):
# YAML
contact:
name: >
Barnaby Marmaduke Aloysius Benjy Cobweb Dartagnan Egbert Felix Gaspar
Humbert Ignatius Jayden Kasper Leroy Maximilian Neddy Obiajulu Pepin
Quilliam Rosencrantz Sexton Teddy Upwood Vivatma Wayland Xylon Yardley
Zachary Usansky
# JSON
{
"contact": {
"name": "Barnaby Marmaduke Aloysius Benjy Cobweb Dartagnan Egbert Felix Gaspar Humbert Ignatius Jayden Kasper Leroy Maximilian Neddy Obiajulu Pepin Quilliam Rosencrantz Sexton Teddy Upwood Vivatma Wayland
Xylon Yardley Zachary Usansky\n"
}
}