Format Swagger Text Descriptions – 格式化Swagger文本描述

最后修改: 2021年 10月 17日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.绪论

The OpenAPI specification (formerly Swagger specification) standardizes REST API documentation language and is platform agnostic. We can create OpenAPI documents in YAML or JSON formats.

OpenAPI规范(前身为Swagger规范)对REST API文档语言进行了标准化,并且与平台无关。我们可以创建YAML或JSON格式的OpenAPI文档

On the other hand, Swagger is a collection of tools for implementing and working with the standard. Some are free, some are open-source, and some are commercial. These tools help us to design, document and consume the REST APIs.

另一方面,Swagger是一个用于实现和使用该标准的工具集合。有些是免费的,有些是开源的,有些则是商业的。这些工具帮助我们设计、记录和消费REST API。

In this article, we’ll learn how to format text descriptions in our OpenAPI documents.

在这篇文章中,我们将学习如何在我们的OpenAPI文档中格式化文本描述。

2. OpenAPI Editors

2.OpenAPI 编辑器

Several tools support us in creating OpenAPI documents. A few popular tools are:

有几个工具支持我们创建OpenAPI文档。几个流行的工具是。

Several other editors provide support in creating OpenAPI documents. However, the most popular and widely used editor is Swagger Editor. Hence, we’ll learn about formatting our OpenAPI documents with the help of Swagger Editor.

其他几个编辑器提供了对创建OpenAPI文档的支持。然而,最流行和最广泛使用的编辑器是Swagger编辑器。因此,我们将学习如何在Swagger编辑器的帮助下格式化我们的OpenAPI文档。

3. YAML vs. JSON Formatting

3.YAML与JSON格式化

An OpenAPI document is represented either in JSON or YAML format. However, formatting the documentation is straightforward while using YAML.

一个OpenAPI文档可以用JSON或YAML格式表示。然而,在使用YAML时,文档的格式化是直接的。

For instance, to mark a word or a sentence as a heading, we use the below snippet in YAML:

例如,为了将一个词或一个句子标记为标题,我们在YAML中使用以下片段。

 description: |
    # This is a heading in *italics*
    This is in the next line
    
    This is in **bold**

The YAML representation uses a | (pipe) to represent scalar literals, which can be multi-line.

YAML表示法使用|(管道)来表示标量字,可以是多行。

Now, Let’s define the same thing in JSON:

现在,让我们在JSON中定义同样的东西。

{
    "description": "# This is a heading in *italics*\nThis is in the next line\n\nThis is in **bold**
}

Comparatively, in JSON representation, the escape sequences make the formatting counter-intuitive. Henceforth, we’ll only look at formatting techniques for OpenAPI specification documents written in YAML.

相对而言,在JSON表示中,转义序列使格式化变得不直观。因此,我们将只看用YAML编写的OpenAPI规范文档的格式化技术。

Finally, OpenAPI specification allows the formatting of description fields at all levels. Thus, according to the specification, wherever the description field is permissible, we can format it, and the description field conforms to the CommonMark formatting style.

最后,OpenAPI规范允许在所有级别上对description字段进行格式化。因此,根据规范,凡是允许description字段的地方,我们都可以对其进行格式化,而且description字段符合CommonMark格式化风格。

Now, let’s enhance our API documents by formatting them.

现在,让我们通过格式化来增强我们的API文档。

4. Headings

4.标题

Like we use <h1> to <h6> headings in HTML, we can use markdown headings to highlight the text. A # represents a heading. We can use # up to six levels to emphasize the text. The higher the number of #, the lesser the text emphasis is.

就像我们在HTML中使用<h1><h6>标题一样,我们可以使用markdown标题来强调文本。一个#代表一个标题我们可以使用#最多六级来强调文本。#的数量越多,文本的强调程度就越小。

A text followed by a # is brighter and bigger than a text accompanied by ######.

跟在#后面的文字比跟在######后面的文字更明亮、更大。

For instance, consider the YAML:

例如,考虑YAML。

openapi: 3.0.1
info:
  title: Petstore
  description: |
    # Pet Store APIs
    ## This is a sample Petstore server
    ### Contains APIs to manage the pet store
    #### Note that the APIs support Basic Authentication and OAUTH
    ##### The samples contain Request and Response models
    ###### There are status codes defined as well

Swagger renders the text as:

Swagger将该文本演绎为:。

5. Text Emphasis

5.文本强调

To enhance the readability of the description text, we can emphasize it by making it bold or italic.

为了提高描述文本的可读性,我们可以通过加粗或斜体来强调它。

Placing a text between ** and ** or within __ and __ makes the text bold. Similarly, placing the text within * and * or _ and _ will make the text italics. For instance, for the YAML:

将文本放在****之间,或放在____之内,将使文本变成粗体。同样,将文本放在*和*或_和_内会使文本变成斜体。例如,对于YAML。

openapi: 3.0.1
info:
  title: Petstore
  description: |
    ## This document contains  
    
    **Pet Store APIs** *Note: All the APIs return application/json*.  
    __User APIs__  _Note: These APIs contain attachments and only support image/jpeg as the content type_

Swagger renders the YAML as:

Swagger将YAML渲染为。

6. Tables

6.桌子

Next, let’s see how to add tables to our OpenAPI documents.

接下来,让我们看看如何向我们的OpenAPI文档添加表格。

There are a set of rules to be followed to render tables. Firstly, each column in the table should start and end with a | (pipe) symbol. Secondly, divide each of the table headers with at least one – (hyphen) symbol. However, the maximum number of – (hyphen) is not restricted.

有一套规则需要遵循,以呈现表格。首先,表格中的每一列都应该以|(管道)符号开始和结束。其次,每个表头至少要用一个-(连字符)符号来分割。然而,-(连字符)的最大数量没有限制。

For instance, let’s add a table to define HTTP status codes for our POST API:

例如,让我们添加一个表,为我们的POST API定义HTTP状态代码。

paths:
  /pet:
    post:
      tags:
      - pet
      description: |
        
        **The below table defines the HTTP Status codes that this API may return**
        
        | Status Code      | Description | Reason                             |
        | ---------------- | ------------| -----------------------------------|
        | 201              | CREATED     | If a pet is created successfuly.   |
        | 400              | BAD REQUEST | If the request is not valid.       |
        | 401              | UNAUTHORIZED| If the credentials are invalid.    |

Swagger generates:

斯瓦格产生了。

7. Lists

7.列表

Now, let’s see how to format the description text to contain lists.

现在,让我们看看如何格式化描述文本以包含列表。

7.1. Ordered List

7.1.有序列表

The description text items should start with a number followed by a . (period). However, the numbering order of the items isn’t essential. That is, the snippets:

描述文本项目应以数字开头,后面是。(period)。然而,项目的编号顺序并不重要。就是说,这些片段。

description: |
  1. Available
  3. Pending
  1. Sold
description: |
  1. Available
  200. Pending
  30. Sold
description: |
  1. Available
  100. Pending
  50. Sold

generate the same output:

产生相同的输出。

1. Available
2. Pending
3. Sold

The numbering of the items depends on the starting item. For instance, if we start the item number with 10, the following items will be numbered 11, 12, 13, etc. The below YAML:

项目的编号取决于起始项目。例如,如果我们以10开始项目编号,下面的项目将被编号为111213,等等。下面的YAML。

description: |
  10. Available
  120. Pending
  50. Sold

generates:

产量。

10. Available
11. Pending
12. Sold

Similarly, the same rules apply for ordered sub-lists as well. Indent a sub-list to its parent item. As an example, consider the YAML:

同样,同样的规则也适用于有序的子列表。缩进一个子列表到它的父项。作为一个例子,考虑YAML。

description: |
  1. Available
  2. Pending
     1. Pending in Store
     200. Pending in Cart
  3. Sold

which generates:

其中产生的。

1. Available
2. Pending
    1. Pending in Store
    2. Pending in Cart
3. Sold

7.2. Unordered List

7.2.无序列表

Use * (asterisks) or + (plus) or a – (hyphen) to create an unordered list. That is, each item in the list should begin with one of these symbols. For example:

使用*(星号)+(加号)-(连字符)来创建一个无序列表。也就是说,列表中的每个项目都应该以这些符号之一开始。比如说。

description: |
  * Available
  * Pending
  * Sold

description: |
  + Available
  + Pending
  + Sold

description: |
  - Available
  - Pending
  - Sold

all the above snippets generate an unordered list.

以上所有的片段都会生成一个无序的列表。

Similarly, to generate unordered sub-lists, indent the items with their parent item and start with a * (asterisks) or + (plus) or a – (hyphen). For instance, the YAML:

同样,要生成无序的子列表,请将项目与其父项目缩进,并以*(星号)+(加号)-(连字符)开始。例如,YAML。

- Available
- Pending
   * Pending in Store
   + Pending in Cart
- Sold

generates an unordered list with a sub-list. Note the mix and match of the delimiters. It is possible to mix the delimiters, which create the same results.

生成一个带有子列表的无序列表。注意定界符的混合和匹配。可以混合定界符,产生同样的结果

Finally, let’s place all this together into a YAML:

最后,让我们把所有这些放到YAML中。

/pet/findByStatus:
   get:
     summary: Finds Pets by status
     description: | 
       __Below is the list of valid status of the Pet__  
        
       1. Available
       2. Pending
          1. Pending in the cart
          2. Pending in the store 
       3. Sold  
        
       **Below is the list of HTTP Status code this API may return**
       * 200 - OK
       * 400 - Bad Request. The API returns below status codes related to content-type and accept headers
         + 415 - Unsupported Media Type
         - 406 - Not Acceptable
       * 401 - Unauthorized
       * 405 - Method not supported

This YAML generates:

这个YAML生成的。

8. Miscellaneous

8.杂项

8.1. Line Breaks and Paragraphs

8.1.分行和段落

Next, to insert a linebreak, type two spaces and the return key. Note that just providing a return key does not align the text to the following line. Similarly, to insert a paragraph, insert an empty line.
Now, let’s add a few line breaks and paragraphs to our description:
description: |
  Returns a single pet.  
  *Note: The API may throw a HTTP 404 if there are no pets found with a given id.*
  
  The API returns a 200 OK if there is a pet with given Id. Also, this API returns the status of the pet
  

This YAML generates:

这个YAML生成的。

8.2. Code

8.2.代码

Next, let’s add a bit of code to our OpenAPI document. Code blocks start and end with “`. For example, consider the YAML:
description: |
  The API returns user details for a given username. 
  The API can be invoked using *curl* like below:
  ```
  curl --header accept: application/json -u username:password http://localhost:8080/api/v2/user/jhondoe
  ```
  **Sample Output**
  ```
  {
    "id": 2,
    "username": "jhondoe"
    "email": "jhon.doe@mail.com"
  }
  ```
The above YAML generates:

8.3. Images

8.3.图像

Finally, to add an image to the document, the image has to be added to description text in the format:
![Alt Text](<path to image>)
Swagger uses the Alt Text when the images fail to load or when we hover over the image. Also, the path to the image could be absolute or relative. Consider the YAML:
description: |
   # Pet Store APIs
   ![Baeldung](https://www.baeldung.com/wp-content/uploads/2017/06/homepage-weekly_reviews.jpg)
Swagger generates:

9. Conclusion

9.结语

In this article, we have seen how to format the description field in our OpenAPI documents. YAML scalar literals enable the formatting of the description across the document. Consequently, an OpenAPI document can contain any or all of the supported constructs, such as lists, tables, and images.

在这篇文章中,我们已经看到了如何在我们的OpenAPI文档中格式化描述字段。YAML 标量字可以在整个文档中对描述进行格式化。因此,一个OpenAPI文档可以包含任何或所有支持的结构,如列表、表格和图像。

Thus, documenting an API improves the ease of use. After all, well-documented and formatted APIs are what we all want for easy integrations and consumption.

因此,记录一个API可以提高使用的便利性。毕竟,文档化和格式化的API是我们都想要的,以方便整合和消费。