同样你也可以在以下路径操作中使用status_code参数来声明Http的status code
- @app.get()
- @app.post()
- @app.put()
- @app.delete()
eg:
from fastapi import FastAPI
app = FastAPI()
@app.post("/items/", status_code=201)
async def create_item(name: str):
return {"name": name}
注意:status_code和response_model一样是方法装饰器的参数,不是函数的参数。
这个status_code将会接收http的状态码。
关于http 状态码
在http中将会发送3位数字作为响应的一部分。
数字信息:
- 100 以及以上的数字代表“information”,很少直接使用到他们,当使用他们的时候响应中不能包含body
- 200以及以上的数字代表“success",他们会经常被使用到,200是默认状态码,意味着所有的都ok,201是”created“经常用于在数据库中创建新纪录以后。204是特殊的,是”no content".当响应给client的body没有content的时候。
- 300以及以上的数字代表“redirection”,
- 400以及以上的数字代表“client error”,404,代表“not found”,一般的客户端错误可以直接使用400.
- 500以及以上的数字代码“server error”,基本上不会用到。
fastapi中有方便的变量,fastapi.status
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}