Technology Sharing

FastAPI Learning Road (Forty-one) Customized Return Response

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

The interface returns the content in XML format

  1. from fastapi import FastAPI, Response
  2. app = FastAPI()
  3. # ① xml
  4. @app.get("/legacy")
  5. def get_legacy_data():
  6. data = """<?xml version="1.0"?>
  7. <shampoo>
  8. <Header>
  9. Apply shampoo here.
  10. </Header>
  11. <Body>
  12. You'll have to use soap here.
  13. </Body>
  14. </shampoo>
  15. """
  16. return Response(content=data, media_type="application/xml")

Let's look at the actual return:

The returned type is in XML format, indicating that the return is successful.

Customizing headers in interface returns

  1. @app.get("/legacy_with_headers")
  2. def get_legacy_with_headers_data():
  3. headers = {"X-Xtoken": "LC", "Content-Language": "en-US"}
  4. data = """<?xml version="1.0"?>
  5. <shampoo>
  6. <Header>
  7. Apply shampoo here.
  8. </Header>
  9. <Body>
  10. You'll have to use soap here.
  11. HERE SOMETHING HEADER YOU DEFINED
  12. </Body>
  13. </shampoo>
  14. """
  15. return Response(content=data, media_type="application/xml", headers=headers)

Let's look at the actual return

The corresponding interface can return normally, and the corresponding Headers return normally.

Setting cookies

  1. @app.get("/legacy_with_header_cookie")
  2. def legacy_with_header_cookie():
  3. headers = {"X-Xtoken": "LC-1", "Content-Language": "en-US"}
  4. data = """<?xml version="1.0"?>
  5. <shampoo>
  6. <Header>
  7. Apply shampoo here.
  8. </Header>
  9. <Body>
  10. You'll have to use soap here.
  11. HERE SOMETHING HEADER YOU DEFINED AND COOKIE
  12. </Body>
  13. </shampoo>
  14. """
  15. response = Response(content=data, media_type="application/xml", headers=headers)
  16. response.set_cookie(key="cookie_key_lc", value="mrli")
  17. return response

Let's look at the actual return

The interface can return the cookies we set normally, and headers can also be returned normally.