从FastApi响应中删除默认的```申请/json`标头''

发布于 2025-02-12 15:18:23 字数 2779 浏览 0 评论 0原文

我已经采取了这一点( https:https:// fastpi.tiangolo.tiangolo。 com/高级/响应directly/#returning-a-custom-response )示例从FastAPI文档中有关如何从FastAPI应用程序中返回自定义响应的文档。这是我想到的示例代码:

from http.client import responses
from fastapi import FastAPI, Response

app = FastAPI()

response_examples = {
    200: {
        "description": "Success",
        "content": {
            "application/xml": {
                "example": {
                    """<?xml version="1.0"?>
    <shampoo>
    <Header>
        Apply shampoo here.
    </Header>
    <Body>
        You'll have to use soap here.
    </Body>
    </shampoo>
    """
                }
            }
        },
    },
    400: {"description": "An invalid value for header content-type."},
    405: {"description": "Endpoint only supports POST."},
    500: {"description": "Internal server error."},
}


@app.get("/legacy/", responses=response_examples)
def get_legacy_data():
    data = """<?xml version="1.0"?>
    <shampoo>
    <Header>
        Apply shampoo here.
    </Header>
    <Body>
        You'll have to use soap here.
    </Body>
    </shampoo>
    """
    return Response(content=data, media_type="application/xml")

但是,当我查询应用程序的/doc端点时,我的问题是关于打开的API文件。

以下是/docs endpoint响应(在yaml)的相关部分:

openapi: 3.0.2
info:
  title: FastAPI
  version: 0.1.0
paths:
  /legacy/:
    get:
      summary: Get Legacy Data
      operationId: get_legacy_data_legacy__get
      responses:
        '200':
          description: Success
          content:
            application/json:
              schema: {}
            application/xml:
              example:
                - |-
                  <?xml version="1.0"?>
                      <shampoo>
                      <Header>
                          Apply shampoo here.
                      </Header>
                      <Body>
                          You'll have to use soap here.
                      </Body>
                      </shampoo>
                      
        '400':
          description: An invalid value for header content-type.
        '405':
          description: Endpoint only supports POST.
        '500':
          description: Internal server error.

响应application/jsonapplication> application> application/xml << /代码>是正确的响应标头。根本不应该有application/json响应。

我的问题是在FastApi中可以做到这一点,如果这样,我如何从响应中删除默认的application/json标题。

I have taken this (https://fastapi.tiangolo.com/advanced/response-directly/#returning-a-custom-response) example from fastapi documentation regarding how to return a custom response from a fastapi application. This is my example code that i came up with to test it :

from http.client import responses
from fastapi import FastAPI, Response

app = FastAPI()

response_examples = {
    200: {
        "description": "Success",
        "content": {
            "application/xml": {
                "example": {
                    """<?xml version="1.0"?>
    <shampoo>
    <Header>
        Apply shampoo here.
    </Header>
    <Body>
        You'll have to use soap here.
    </Body>
    </shampoo>
    """
                }
            }
        },
    },
    400: {"description": "An invalid value for header content-type."},
    405: {"description": "Endpoint only supports POST."},
    500: {"description": "Internal server error."},
}


@app.get("/legacy/", responses=response_examples)
def get_legacy_data():
    data = """<?xml version="1.0"?>
    <shampoo>
    <Header>
        Apply shampoo here.
    </Header>
    <Body>
        You'll have to use soap here.
    </Body>
    </shampoo>
    """
    return Response(content=data, media_type="application/xml")

However my question is regarding the open api file when I am querying the /docs endpoint of my application.

Below is the relevant section of the /docs endpoint response(in yaml):

openapi: 3.0.2
info:
  title: FastAPI
  version: 0.1.0
paths:
  /legacy/:
    get:
      summary: Get Legacy Data
      operationId: get_legacy_data_legacy__get
      responses:
        '200':
          description: Success
          content:
            application/json:
              schema: {}
            application/xml:
              example:
                - |-
                  <?xml version="1.0"?>
                      <shampoo>
                      <Header>
                          Apply shampoo here.
                      </Header>
                      <Body>
                          You'll have to use soap here.
                      </Body>
                      </shampoo>
                      
        '400':
          description: An invalid value for header content-type.
        '405':
          description: Endpoint only supports POST.
        '500':
          description: Internal server error.

There are 2 header types mentioned in the response application/json and application/xml which is the right response header. There should not be an application/json response at all.

My question is that is this possible to do in fastapi and if so how can i remove the default application/json header from response.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

苏佲洛 2025-02-19 15:18:23

您应该在端点中放入response_class =参数。以下是一个完全有效的例子:

from fastapi import FastAPI, Response

app = FastAPI()

response_examples = {
    200: {
        "description": "Success",
        "content": {
            "application/xml": {
                "example": {
                    """<?xml version="1.0"?>
    <shampoo>
    <Header>
        Apply shampoo here.
    </Header>
    <Body>
        You'll have to use soap here.
    </Body>
    </shampoo>
    """
                }
            }
        },
    },
    400: {"description": "An invalid value for header content-type."},
    405: {"description": "Endpoint only supports POST."},
    500: {"description": "Internal server error."},
}

class XMLResponse(Response):
    media_type = "application/xml"



@app.get("/legacy/", responses=response_examples, response_class=XMLResponse)
def get_legacy_data():
    data = """<?xml version="1.0"?>
    <shampoo>
    <Header>
        Apply shampoo here.
    </Header>
    <Body>
        You'll have to use soap here.
    </Body>
    </shampoo>
    """
    return XMLResponse(content=data)

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000,  )

结果:

You should put in a response_class= parameter in your endpoint. Below is a fully working example:

from fastapi import FastAPI, Response

app = FastAPI()

response_examples = {
    200: {
        "description": "Success",
        "content": {
            "application/xml": {
                "example": {
                    """<?xml version="1.0"?>
    <shampoo>
    <Header>
        Apply shampoo here.
    </Header>
    <Body>
        You'll have to use soap here.
    </Body>
    </shampoo>
    """
                }
            }
        },
    },
    400: {"description": "An invalid value for header content-type."},
    405: {"description": "Endpoint only supports POST."},
    500: {"description": "Internal server error."},
}

class XMLResponse(Response):
    media_type = "application/xml"



@app.get("/legacy/", responses=response_examples, response_class=XMLResponse)
def get_legacy_data():
    data = """<?xml version="1.0"?>
    <shampoo>
    <Header>
        Apply shampoo here.
    </Header>
    <Body>
        You'll have to use soap here.
    </Body>
    </shampoo>
    """
    return XMLResponse(content=data)

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000,  )

The outcome:
enter image description here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文