You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Connexion如何设置响应Content-Type?能否在接口函数中配置?

How to Set Response Content-Type in Connexion?

Great question! Yes, you absolutely can set the Content-Type header directly in your post_order function — and it’s a straightforward fix that will override the default behavior you’re running into.

Why Your Current Setup Works the Way It Does

When your OpenAPI spec lists multiple content types for a response (like both application/json and text/plain), Connexion defaults to using the first one it encounters (in your case, application/json). That’s why you keep seeing that header even though text/plain is also defined. When you removed application/json from the spec, Connexion had no other option but to use text/plain — which is why that scenario worked.

Fix: Return a Tuple with Custom Headers

The simplest way to force a specific Content-Type is to return a tuple from your endpoint function, containing three elements:

  1. The response body
  2. The HTTP status code
  3. A dictionary of custom headers

Here’s how to modify your post_order function to do this:

def post_order(platform, open_req=None): # noqa: E501
    """order """
    # Return (response body, status code, headers)
    return 'do some magic!', 200, {'Content-Type': 'text/plain; charset=utf-8'}

This will override any default Content-Type from your OpenAPI spec — even if you leave both application/json and text/plain listed in the YML. The header defined in your function takes precedence.

Alternative: Use Connexion’s Response Object

If you need more control over your response (like setting additional headers or cookies), you can use Connexion’s built-in Response object instead:

from connexion import Response

def post_order(platform, open_req=None): # noqa: E501
    """order """
    response = Response(response='do some magic!', status_code=200)
    response.headers['Content-Type'] = 'text/plain; charset=utf-8'
    # Add any other headers you need here
    # response.headers['X-Custom-Header'] = 'value'
    return response

Both methods work reliably, but the tuple approach is ideal for simple cases like yours.

内容的提问来源于stack exchange,提问作者Song

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 10:52:44