接口中返回xml格式内容
from fastapi import FastAPI, Response
app = FastAPI()
# ① xml
@app.get("/legacy")
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")
我们看下实际返回:
返回的类型是xml格式的,说明返回成功。
接口返回中定制headers
@app.get("/legacy_with_headers")
def get_legacy_with_headers_data():
headers = {"X-Xtoken": "LC", "Content-Language": "en-US"}
data = """<?xml version="1.0"?>
<shampoo>
<Header>
Apply shampoo here.
</Header>
<Body>
You'll have to use soap here.
HERE SOMETHING HEADER YOU DEFINED
</Body>
</shampoo>
"""
return Response(content=data, media_type="application/xml", headers=headers)
我们看下实际返回
对应的接口可以正常返回,对应的Headers返回正常。
设置cookie
@app.get("/legacy_with_header_cookie")
def legacy_with_header_cookie():
headers = {"X-Xtoken": "LC-1", "Content-Language": "en-US"}
data = """<?xml version="1.0"?>
<shampoo>
<Header>
Apply shampoo here.
</Header>
<Body>
You'll have to use soap here.
HERE SOMETHING HEADER YOU DEFINED AND COOKIE
</Body>
</shampoo>
"""
response = Response(content=data, media_type="application/xml", headers=headers)
response.set_cookie(key="cookie_key_lc", value="mrli")
return response
我们看下实际返回
接口可以正常返回我们设置的cookie,headers也可以正常返回。