FastAPI之 HTTP响应
默认情况下,FastAPI会把你的端点函数所返回的内容转为JSON格式。返回的HTTP响应,包含一行内容为Content-type:application/json的Header信息。即便返回的是一个字符串,也会转为JSON。
状态码
在默认情况下,FastAPI返回的状态码是200,如果是异常,返回对应的是4**状态码。
- 指定成功状态码
@app.get("/hello",status_code=200)
async def say_hello():return "hello world"
status_code
可以写数字,也可以用 from fastapi import status
里的枚举:
from fastapi import status
@app.post("/items", status_code=status.HTTP_201_CREATED)
-
返回自定义成功码 + 响应体
from fastapi import Response@app.post("/report")
def generate_report(response: Response):response.status_code = 202 # ← 202