【问题标题】:How does Connexion set the response content type?Connexion 如何设置响应内容类型?
【发布时间】:2025-11-27 10:20:17
【问题描述】:

以下是 API *.yml 部分。我想将数据的响应头设置为Content-type: text/plain,但它现在总是返回application/json

  /order:
    post:
      tags:
        - order
      summary: order
      operationId: PostOrder
      parameters:
      requestBody:
        description: Order result
        content:
          application/json:
            schema:
              type: object
              properties:
                openReq:
                  type: string
                  example: 'test'

      responses:
        200:
          description: Customer order receive successed
          headers: {}
          content:
            application/json:
              schema:
                type: string
            text/plain:
              schema:
                type: string

此python代码返回响应:

def post_order(platform, open_req=None):  # noqa: E501
    """order

    """
    return 'do some magic!'

响应头总是content-type: application/json

      responses:
        200:
          description: Customer order receive successed
          headers: {}
          content:
            application/json:
              schema:
                type: string
            text/plain:
              schema:
                type: string

这个 sn-p 的这个响应头总是content-type: text/plain; charset=utf-8

      responses:
        200:
          description: Customer order receive successed
          headers: {}
          content:
#            application/json:
#              schema:
#                type: string
            text/plain:
              schema:
                type: string

我可以在函数post_order中设置响应头内容类型吗?

【问题讨论】:

  • 你的定义是有效的。您能否更详细地解释问题是什么以及何时发生?即使客户端请求text/plain,您的 API 服务器是否总是返回 JSON?还是别的什么?

标签: swagger openapi connexion


【解决方案1】:

如果您希望您的函数动态决定返回哪种内容类型,您必须按照documentation 中的说明明确设置标头。

这两种方法之一是返回内容元组、返回码和标题字典,如下所示:

def post_order(platform, open_req=None): 
    """order

    """
    return 'do some magic!', 200, {'content-type': 'text/plain'}

第二种方法是显式创建响应对象并返回:

from connexion.lifecycle import ConnexionResponse

def post_order(platform, open_req=None): 
    """order

    """
    return ConnexionResponse(
        status_code=200,
        content_type='text/plain',
        body='do some magic!'
    )

这让您可以更好地控制其他调整。但是,如果简单的元组解决方案适用于您的情况,则没有必要。

【讨论】:

    【解决方案2】:

    也许您将 API Swagger Docs 与实际实现混淆了,您的文档是正确的,这意味着响应 200 OK,可以返回为 application/jsontext/plain。返回哪一个完全取决于端点的实现。如果您的端点只返回application/json,那么您将永远不会收到text/plain,那不是Swagger/OpenApi 的Job。

    【讨论】:

    • 抱歉回复晚了,你知道connexion如何设置响应头类型