用YAML生成Swagger格式的API Documentation

在工作当中,会遇到需要写API文档的情况。最开始,在网上搜现成的django-rest-swagger,用了之后发现,不是很好用,没办法一次成型的解决问题。后来,就直接本办法,把yaml转化成swagger的html,就是套django模板啦(render)。yaml语法和json宗旨是差不多的,都是list和dict的结合。swagger就是一种内容特定化的yaml文件。

YAML的view如下(一个view函数):

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’):





  
   Swagger UI 
  
  
  


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: []
...

你可能感兴趣的:(用YAML生成Swagger格式的API Documentation)