用YAML生成Swagger格式的API Documentation

在工作當(dāng)中,會遇到需要寫API文檔的情況。最開始,在網(wǎng)上搜現(xiàn)成的django-rest-swagger,用了之后發(fā)現(xiàn),不是很好用,沒辦法一次成型的解決問題。后來,就直接本辦法,把yaml轉(zhuǎn)化成swagger的html,就是套django模板啦(render)。yaml語法和json宗旨是差不多的,都是list和dict的結(jié)合。swagger就是一種內(nèi)容特定化的yaml文件。

YAML的view如下(一個view函數(shù)):

def yaml2html(request):
    import yaml, json, sys

    with open('templates/test.yaml', 'r') as stream:
        try:
            yaml_string = json.dumps(yaml.load(stream))

        except yaml.YAMLError as e:
            print(e)
            return HttpResponse("Error!")

    return render(request, 'yaml-template.html', {'yaml_string': yaml_string})

模板如下(html模板,替換字符串,記住要加 ‘|safe’):


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title> Swagger UI </title>
  <link  rel="stylesheet">
  <link rel="stylesheet" type="text/css"  >
  <style>
    html
    {
      box-sizing: border-box;
      overflow: -moz-scrollbars-vertical;
      overflow-y: scroll;
    }
    *,
    *:before,
    *:after
    {
      box-sizing: inherit;
    }
    body {
      margin:0;
      background: #fafafa;
    }
  </style>
</head>
<body>
<div id="swagger-ui"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/3.2.2/swagger-ui-bundle.js"> </script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/3.2.2/swagger-ui-standalone-preset.js"> </script>
<script>
window.onload = function() {
  var spec = {{ yaml_string|safe }};
  // Build a system
  const ui = SwaggerUIBundle({
    spec: spec,
    dom_id: '#swagger-ui',
    deepLinking: true,
    presets: [
      SwaggerUIBundle.presets.apis,
      SwaggerUIStandalonePreset
    ],
    plugins: [
      SwaggerUIBundle.plugins.DownloadUrl
    ],
    layout: "StandaloneLayout"
  })
  window.ui = ui
}
</script>
</body>
</html>

YAML文件:

---
swagger: "2.0"

openapi: 3.0.0
info:
  description: Book API
  title: Book API
  version: 0.0.0-alpha
schemes:
  - http
servers:
  - url: 'http://localhost:8080'
  - url: 'http://localhost:8082'
paths:
  '/books/books':
    get:
      summary: get all books.
      description: Get All Books.
      parameters:
        - name: book_id
          in: query
          schema:
            type: integer
          required: false
          description: Id of the book
      tags:
        - Books
      responses:
        '200':
          description: Books retrieved.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/projectResponse'
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/projectRequest'
      security:
        - api_key: []
...
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 模塊間聯(lián)系越多,其耦合性越強,同時表明其獨立性越差( 降低耦合性,可以提高其獨立性)。軟件設(shè)計中通常用耦合度和內(nèi)聚...
    riverstation閱讀 2,232評論 0 8
  • Web框架之Django: (1)簡介: Django是一個由Python寫成開源的重量級Web應(yīng)用框架,采用MT...
    老肖閱讀 3,168評論 0 18
  • (一)、啟動服務(wù)器 (二)、創(chuàng)建數(shù)據(jù)庫表 或 更改數(shù)據(jù)庫表或字段 Django 1.7.1及以上 用以下命令 1....
    夏天夏星閱讀 5,982評論 0 17
  • 模板標(biāo)簽除了幾個常用的,還真心沒有仔細(xì)了解一下,看到2.0發(fā)布后,翻譯學(xué)習(xí)一下。 本文盡量忠實原著,畢竟大神的東西...
    海明_fd17閱讀 2,141評論 0 5
  • 天漸漸變暗了,天空中布滿云層,大街上空無一人……只有似活非活著的陸萱還走在街上,她感覺自己的身體已經(jīng)不屬于自己了,...
    余言i閱讀 201評論 0 1

友情鏈接更多精彩內(nèi)容