[英]How to use custom YAML file as API documentation in Django REST Framework?
我需要将 API 文档添加到我的项目中。 我使用 swagger 编辑器编写了我的自定义模式,现在我有一个 YAML 文件,如下所示:
swagger: "2.0"
info:
description: "This is the documentation of Orion Protocol API"
version: "1.0.0"
title: "Orion Protocol API"
host: "127.0.0.1:8000"
basePath: "/api/"
paths:
/api/decode:
post:
tags:
- "pet"
summary: "Decode the payload"
consumes:
- "application/json"
produces:
- "application/json"
parameters:
- in: "body"
name: "body"
description: "Packet data"
required: true
schema:
$ref: "#/definitions/PacketData"
responses:
"405":
description: "Invalid input"
/api/encode:
post:
description: "Encoding configuration parameters for the devices"
produces:
- "string"
parameters:
- in: "body"
name: "body"
description: "Addresses and values of configuration parameters"
required: true
schema:
$ref: "#/definitions/ConfigPayload"
responses:
"405":
description: "Invalid input"
definitions:
PacketData:
type: "object"
required:
- "payload"
properties:
payload:
type: "string"
description: "Packet string starting with 78"
example: "78010013518BB325140400000500000AAA0000002A6E0000004AC05D00006A00000000"
ConfigPayload:
type: "object"
properties:
Addresses of the configuration parameter:
type: "string"
description: "According to the documentation of configuration protocol"
example: "542"
现在如何将其添加到项目中? 它应该位于项目中的什么位置? 视图可以渲染这个文件吗? 我需要有以下路径:
urlpatterns = [
path('documentation/', some-view-that-will-render-yaml)
]
我找到了解决方案,而且非常简单。 我们需要将 yaml 转换为 json 并保存在 static 文件夹中。 然后:urls.py
urlpatterns = [
...
path('swagger-ui/', TemplateView.as_view(
template_name='swagger-ui.html',
extra_context={'schema_url': 'openapi-schema'}
), name='swagger-ui'),
]
模板/swagger-ui.html:
{% load static %}
<html>
<head>
<title>Documentation</title>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="//unpkg.com/swagger-ui-dist@3/swagger-ui.css" />
</head>
<body>
<div id="swagger-ui"></div>
<script src="//unpkg.com/swagger-ui-dist@3/swagger-ui-bundle.js"></script>
<script>
const ui = SwaggerUIBundle({
url: "{% static 'swagger.json' %}" ,
dom_id: '#swagger-ui',
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIBundle.SwaggerUIStandalonePreset
]
})
</script>
</body>
</html>
并将您的自定义模式保存为 json 在 static 文件夹中。 作品!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.