如何在Django REST Framework中将自定义YAML文件用作API文档? [英] How to use custom YAML file as API documentation in Django REST Framework?
问题描述
我需要将API文档添加到我的项目中.我使用swagger编辑器编写了自定义架构,现在有一个YAML文件,如下所示:
I need to add API documentation to my project. I wrote my custom schema using swagger editor and now I have a YAML file as follows:
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"
现在如何将其添加到项目中?它应该在项目中的什么位置?视图可以渲染该文件吗?我需要使用以下路径:
Now how can I add this to the project? Where it should locate in the project? May the views render this file? I need to have the following path:
urlpatterns = [
path('documentation/', some-view-that-will-render-yaml)
]
推荐答案
我找到了解决方案,这很容易.我们需要将yaml转换为json并将其保存在静态文件夹中.然后:urls.py
I found a solution and it was pretty easy. We need to convert yaml to json and save it in static folder. Then: urls.py
urlpatterns = [
...
path('swagger-ui/', TemplateView.as_view(
template_name='swagger-ui.html',
extra_context={'schema_url': 'openapi-schema'}
), name='swagger-ui'),
]
templates/swagger-ui.html:
templates/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到静态文件夹中.有效!
and save your custom schema as json in static folder. Works!
这篇关于如何在Django REST Framework中将自定义YAML文件用作API文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!