返回
FastAPI 超强教程 | 轻松请求处理和响应返回
后端
2023-09-08 14:20:48
纵览 FastAPI 请求参数和响应
FastAPI 是一个现代化的 Python 框架,专门为构建 API 而设计。它提供了简洁的语法和丰富的功能,让开发人员能够轻松快速地创建高性能、高安全的 API。
在 FastAPI 中,请求参数和响应是通过函数参数和返回值来定义和处理的。函数参数代表传入的请求参数,函数返回值代表发出的响应。
1. URL 路径参数
URL 路径参数是指通过在 URL 的斜杠后面传递的参数。例如,在 URL "/user/{id}" 中,"{id}" 就是一个 URL 路径参数,它代表用户的 ID。
from fastapi import FastAPI, Path
app = FastAPI()
@app.get("/user/{id}")
async def get_user(id: int = Path(..., gt=0)):
return {"user_id": id}
2. 请求体参数
请求体参数是指通过请求体传递的参数。请求体参数通常用于提交表单数据或 JSON 数据。
from fastapi import FastAPI, Body
app = FastAPI()
@app.post("/user")
async def create_user(user: dict = Body(...)):
return user
3. 响应体返回
响应体返回是指通过 HTTP 响应体返回的数据。响应体返回的数据可以是任何格式,例如 JSON、HTML 或文本。
from fastapi import FastAPI, JSONResponse
app = FastAPI()
@app.get("/hello")
async def hello():
return JSONResponse(content={"message": "Hello, world!"})
4. 自定义状态码
FastAPI 允许开发人员自定义响应的状态码。
from fastapi import FastAPI, HTTPException
app = FastAPI()
@app.get("/protected")
async def protected():
raise HTTPException(status_code=401, detail="Unauthorized")
5. 请求头
FastAPI 可以通过请求头获取客户端发送的请求信息,如:
from fastapi import FastAPI, Request
app = FastAPI()
@app.get("/user-agent")
async def user_agent(request: Request):
user_agent = request.headers.get("User-Agent")
return {"user_agent": user_agent}
6. HTTP 方法
FastAPI 支持所有常用的 HTTP 方法,包括:
GET
POST
PUT
DELETE
7. 文档自动生成
FastAPI 可以自动生成 API 文档,只需在函数上使用 @app.get
, @app.post
, @app.put
, @app.delete
等装饰器即可。
from fastapi import FastAPI
app = FastAPI()
@app.get("/users")
async def get_users():
"""
获取所有用户
返回:
列表[用户]
"""
return [{"id": 1, "name": "John Doe"}, {"id": 2, "name": "Jane Doe"}]
至此,我们介绍了 FastAPI 中请求参数和响应的处理方式,希望对您有所帮助。如果您有其他问题,欢迎在下方留言。