from fastapi import FastAPI, status app = FastAPI() @app.post("/items/", status_code=201) async def create_item(name: str): return {"name": name} status_code 参数属于装饰器中的参数,而非 路径操作函数 的参数。它接收一个表示 HTTP 状态码的数字,或支持 IntEnum 类型,例如 ...
status_code参数接收表示 HTTP 状态码的数字。 说明 status_code还能接收IntEnum类型,比如 Python 的http.HTTPStatus。 它可以: 在响应中返回状态码 在OpenAPI 概图(及用户界面)中存档: 笔记 某些响应状态码表示响应没有响应体(参阅下一章)。 FastAPI 可以进行识别,并生成表明无响应体的 OpenAPI 文档。
fromfastapiimportFastAPI,statusapp=FastAPI()@app.get("/items/",status_code=status.HTTP_418_IM_A_TEAPOT)defread_items():return[{"name":"Plumbus"},{"name":"Portal Gun"}] fastapi.status¶ HTTP codes See HTTP Status Code Registry: https://www.iana.org/assignments/http-status-codes/http-...
一、 FASTAPI系列 15-响应状态码status_code 前言 与指定响应模型的方式相同,你也可以在以下任意的_路径操作_中使用status_code 参数来声明用于响应的HTTP 状态码: @app.get() @app.post() @app.put() @app.delete() 一、响应状态码 from fastapi import FastAPI app = FastAPI() @app.post(...
status_code参数接收一个表示 HTTP 状态码的数字。 status_code也能够接收一个IntEnum类型,比如 Python 的http.HTTPStatus。 它将会: 在响应中返回该状态码。 在OpenAPI 模式中(以及在用户界面中)将其记录为: ![[Pasted image 20230718112653.png]]
有些场景下要为HTTP错误添加自定义响应头。例如,出于某些方面的安全需要。 我们看下如何自定义响应头 from fastapiimportFastAPI,HTTPException app=FastAPI()items={"test":"雷子说测试开发"}@app.get("/items/{item_id}")defread_item(item_id:str):ifitem_id notinitems:raiseHTTPException(status_code=404,...
Python FastAPI HTTP Status Code When working with web APIs, understanding HTTP status codes is crucial as they convey important information about the success or failure of a request. FastAPI, a modern web framework for building APIs with Python, makes it easy to handle HTTP status codes in a ...
app=FastAPI()@app.post("/items/",status_code=201)defcreate_item(name:str):return{"name":name} 我们用postman请求下。 接口可以正常请求,状态码返回的也是我们定义的201。 在接口文档上也可以正常展示我们成功的状态码 对于http的状态码,每个数字代表不一样的含义。
status_code参数接收一个表示 HTTP 状态码的数字。 status_code也能够接收一个IntEnum类型,比如 Python 的http.HTTPStatus。 它将会: 在响应中返回该状态码。 在OpenAPI 模式中(以及在用户界面中)将其记录为: ![[Pasted image 20230718112653.png]]
在fastapi库中定义了一个status,可以用于更直接地以枚举方式来引用上述各HTTP状态码。相关应用如下所示: from fastapi import FastAPI, **status** app = FastAPI() @app.post("/items/", status_code=status.HTTP_201_CREATED) async def create_item(name: str): ...