debian

Debian Swagger如何支持多种数据格式

小樊
43
2025-11-25 00:27:41
栏目: 智能运维

在 Debian 上让 Swagger 支持多种数据格式

一 核心思路

二 规范层配置示例

openapi: 3.0.3
info:
  title: Multi-Format API
  version: 1.0.0
paths:
  /echo:
    post:
      summary: Echo back the request body in the same format
      description: |
        Accepts **application/json** or **application/xml**.
        Returns the same media type that was sent.
      operationId: echo
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/Message'
            examples:
              sample:
                value:
                  text: Hello JSON
          application/xml:
            schema:
              $ref: '#/components/schemas/MessageXml'
            examples:
              sample:
                value: |-
                  <Message><text>Hello XML</text></Message>
      responses:
        '200':
          description: Echoed content in the requested format
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Message'
            application/xml:
              schema:
                $ref: '#/components/schemas/MessageXml'
components:
  schemas:
    Message:
      type: object
      required: [text]
      properties:
        text:
          type: string
          example: Hello JSON
    MessageXml:
      type: string
      xml:
        name: Message
      example: "<Message><text>Hello XML</text></Message>"

三 服务端实现要点

app.use(express.json());                 // application/json
app.use(express.text({ type: 'text/xml' })); // application/xml
app.use(express.urlencoded({ extended: true }));

app.post('/echo', (req, res) => {
  const contentType = req.get('content-type') || '';
  let body;
  if (contentType.includes('application/json')) {
    body = req.body; // 已是对象
  } else if (contentType.includes('application/xml')) {
    // 简单演示:将 XML 文本原样回显;生产可用 fast-xml-parser/xmldom 等解析为对象
    body = { text: req.body };
  } else {
    return res.status(415).send('Unsupported Media Type');
  }
  // 回显相同格式
  const accept = req.get('accept') || '';
  if (accept.includes('application/xml')) {
    res.type('application/xml').send(`<Message><text>${escapeXml(body.text)}</text></Message>`);
  } else {
    res.json(body);
  }
});

四 在 Debian 上的部署与验证

0
看了该问题的人还看了