一、概述
使用response_model定义
请求一个接口返回来我们客户端可见的东西都是所谓的响应报文,如响应头,响应码,响应内容等。
通常不会那么傻的用户输入什么就返回什么。以下的官网示例纯粹的演示看:
import uvicorn from fastapi import FastAPI from pydantic import BaseModel, EmailStr app = FastAPI() class UserIn(BaseModel): username: str password: str email: str full_name: str = None class UserOut(BaseModel): username: str email: str full_name: str = None @app.post("/user/", response_model=UserOut) async def create_user(*, user: UserIn): return user if __name__ == '__main__': uvicorn.run(app='main:app', host="127.0.0.1", port=8000, reload=True, debug=True)
json参数
{ "username":"xiao", "password":"1234", "email":"12345678@qq.com", "full_name":"肖" }
通常再定义我们的API返回响应的时候,一般是返回固定JSON格式的,所以可以直接使用定义response_model为一个字典:
import uvicorn from fastapi import FastAPI from typing import Dict app = FastAPI() @app.get("/keyword-weights/", response_model=Dict[str, float]) async def read_keyword_weights(): return {"foo": 2.3, "bar": 3.4} if __name__ == '__main__': uvicorn.run(app='main:app', host="127.0.0.1", port=8000, reload=True, debug=True)
json参数
{ "username":"xiao", "password":"1234", "email":"12345678@qq.com", "full_name":"肖" }
关于响应状态码status_code
通常的一个接口请求完成,如果没有什么异常通常会返回200: 如日志打印出来一样:
INFO: 127.0.0.1:58141 - "POST /user/ HTTP/1.1" 400 INFO: 127.0.0.1:58315 - "POST /user/ HTTP/1.1" 200
FastAPI运行我们的指定返回的status_code,如下示例:
import uvicorn from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class UserIn(BaseModel): username: str password: str email: str full_name: str = None class UserOut(BaseModel): username: str email: str full_name: str = None @app.post("/user/", response_model=UserOut,status_code=500) async def create_user(*, user: UserIn): return user if __name__ == '__main__': uvicorn.run(app='main:app', host="127.0.0.1", port=8000, reload=True, debug=True)
由于在路由中定死了状态码500,所以这里就是500
甚至还可以通过导入status来指定:
import uvicorn from fastapi import FastAPI, status app = FastAPI() @app.post("/items/", status_code=status.HTTP_201_CREATED) async def create_item(name: str): return {"name": name} if __name__ == '__main__': uvicorn.run(app='main:app', host="127.0.0.1", port=8000, reload=True, debug=True)
访问
http://127.0.0.1:8000/items?name=xiao
可以看到状态码为201
本文参考链接: