Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to draw tables using JSON for OpenAPI

I want to make a table in a JSON file

  • I use Swagger UI (2.0) to describe APIs. The opneapi.json is hosted in a Gitlab.
  • The Swagger Spec says that GFM syntax can be used for rich text representation.
  • The Gitlab flavoured Markdown (GFM) syntax for a table includes a "carriage return".
  • But JSON does not handle "carriage return".

Is there any workaround to include tables in an openapi.json?

like image 350
Clara Baillehache Avatar asked Jan 31 '18 16:01

Clara Baillehache


1 Answers

OpenAPI 2.0

OpenAPI 2.0 uses GitHub Flavored Markdown, which supports the usual Markdown syntax for tables, such as:

| One | Two | Three |
|-----|-----|-------|
| a   | b   | c     |

(example taken from this answer)

In JSON, you would write this as:

// JSON example
"description": "Sample table:\n\n| One | Two | Three |\n|-----|-----|-------|\n| a   | b   | c     |"

The easiest way to get the JSON right is to use http://editor.swagger.io to format and preview the text, and then download the definition as JSON.

In YAML, make sure the indentation is correct (all lines in multiline text need to be indented related to the key name):

# YAML example
swagger: '2.0'
info:
  version: 0.0.0
  title: Table demo
  description: |
    Sample table:

    | One | Two | Three |
    |-----|-----|-------|
    | a   | b   | c     |
paths: {}

OpenAPI 3.0

OpenAPI 3.0 Specification states that tools must support, at a minimum, CommonMark v. 0.27+, and might support additional Markdown syntax on top of CommonMark.

CommonMark itself does not have table syntax, but you can use the HTML <table> element as a workaround:

// JSON example
"description": "Sample table:\n\n<table><tr><td>One</td><td>Two</td><td>Three</td></tr><tr><td>a</td><td>b</td><td>c</td></tr></table>"

And in YAML:

openapi: 3.0.0
info:
  version: 0.0.0
  title: Table demo
  description: |
    Sample table:

    <table>
      <tr>
        <td>One</td>
        <td>Two</td>
        <td>Three</td>
      </tr>
      <tr>
        <td>a</td>
        <td>b</td>
        <td>c</td>
      </tr>
    </table>
paths: {}


That said, Swagger UI v. 3.22.0+ and Swagger Editor v. 3.6.27+ support GFM table syntax for OAS3 (in addition to CommonMark), so the users of these tools can use the familiar Markdown table syntax:

# Works in Swagger UI and Swagger Editor
openapi: 3.0.0
info:
  version: 0.0.0
  title: Table demo
  description: |
    Sample table:

    | One | Two | Three |
    |-----|-----|-------|
    | a   | b   | c     |
paths: {}
like image 82
Helen Avatar answered Nov 15 '22 11:11

Helen