如何在FastAPI中灵活使用路径参数、查询参数和请求体参数进行接口设计

In FastAPI, you can handle different types of parameters in your endpoints, such as path parameters, query parameters, and request body parameters. Each type of parameter is handled differently depending on how it is defined in the endpoint function.

1. Path Parameters

Path parameters are part of the URL path. They are typically used to pass resources or identifiers that are part of the route, for example, /items/{item_id}.

Example:

python 复制代码
@app.put("/items/{item_id}")
async def read_item(item_id: int):
    return {"item_id": item_id}

2. Query Parameters

Query parameters are part of the URL after the ? symbol, and they are used to pass additional data to the request. They are typically used with GET or PUT requests and are defined as function parameters without braces.

Example with a single query parameter:

python 复制代码
@app.put("/items/")
async def read_item(item_id: int):
    return {"item_id": item_id}

To test this with requests:

python 复制代码
import requests
url = 'http://127.0.0.1:8009/items/?item_id=5'
res = requests.put(url)
print(res.text)  # Output: {"item_id": 5}

3. Request Body Parameters

Request body parameters are used when you need to send structured data as the body of the request. These can be either single or multiple parameters passed as JSON in the request body.

Single Request Body Parameter

To specify that a parameter should be in the request body, you use Body().

Example:

python 复制代码
from fastapi import Body, FastAPI

@app.put("/items/")
async def read_item(item_id: int = Body(...)):
    return {"item_id": item_id}

To test with requests:

python 复制代码
import requests
url = 'http://127.0.0.1:8009/items/'
res = requests.put(url, json={"item_id": 5})
print(res.text)  # Output: {"item_id": 5}
Multiple Request Body Parameters

You can also define multiple parameters in the request body by using Body() for each one.

Example:

python 复制代码
from fastapi import Body, FastAPI

@app.put("/items/")
async def read_item(item_id: int = Body(...), name: str = Body(...)):
    return {"item_id": item_id, "name": name}

To test with requests:

python 复制代码
import requests
url = 'http://127.0.0.1:8009/items/'
res = requests.put(url, json={"item_id": 5, "name": "张三"})
print(res.text)  # Output: {"item_id": 5, "name": "张三"}

4. Using Pydantic Models for Request Body

You can also use Pydantic models to define request bodies, which gives you more control and validation over the incoming data.

Example:

python 复制代码
from fastapi import FastAPI
from pydantic import BaseModel

class Item(BaseModel):
    name: str
    description: str | None = None
    price: float
    tax: float | None = None

@app.put("/items/")
async def read_item(item: Item):
    return {"name": item.name, "price": item.price}

To test with requests:

python 复制代码
import requests
url = 'http://127.0.0.1:8009/items/'
data = {"name": "细胞生物学", "description": "考研书籍", "price": 35.8, "tax": 0.6}
res = requests.put(url, json=data)
print(res.text)  # Output: {"name": "细胞生物学", "price": 35.8}

5. Mixed Parameters (Path, Query, and Body)

You can also mix path, query, and body parameters in a single endpoint. FastAPI will automatically handle them correctly.

Example:

python 复制代码
from fastapi import Body, FastAPI

@app.put("/items/{name}")
async def read_item(name: str, age: int, item_id: int = Body(...)):
    return {"name": name, "age": age, "item_id": item_id}

Testing via FastAPI's Documentation

FastAPI also provides a built-in interactive docs interface at /docs that allows you to test all your endpoints directly in the browser. You can input values for query parameters, request body parameters, and see the results.

To access the docs:

  1. Run the FastAPI app.
  2. Open http://127.0.0.1:8009/docs in a browser.
  3. Test your endpoints using the interactive interface by clicking on "Try it out", filling in the parameters, and clicking "Execute".
相关推荐
丶意冷29 分钟前
mybatisPlus分页方言设置错误问题 mybatisPlus对于Oceanbase的Oracle租户分页识别错误
java·数据库·oracle·oceanbase
时序数据说2 小时前
为什么时序数据库IoTDB选择Java作为开发语言
java·大数据·开发语言·数据库·物联网·时序数据库·iotdb
戒不掉的伤怀2 小时前
【Navicat 连接MySQL时出现错误1251:客户端不支持服务器请求的身份验证协议;请考虑升级MySQL客户端】
服务器·数据库·mysql
cv高级工程师YKY2 小时前
服务器 - - QPS与TPS介绍
数据库
nbsaas-boot3 小时前
高可扩展属性建模设计:架构师的全局思考与落地方案
数据库
爱上语文3 小时前
Redis基础(5):Redis的Java客户端
java·开发语言·数据库·redis·后端
陈敬雷-充电了么-CEO兼CTO4 小时前
推荐算法系统系列>推荐数据仓库集市的ETL数据处理
大数据·数据库·数据仓库·数据挖掘·数据分析·etl·推荐算法
MeshddY4 小时前
(超详细)数据库项目初体验:使用C语言连接数据库完成短地址服务(本地运行版)
c语言·数据库·单片机
wuxinyan1234 小时前
Java面试题033:一文深入了解MySQL(5)
java·数据库·mysql·面试
萧曵 丶4 小时前
Spring @TransactionalEventListener
java·数据库·spring·事务·transactional·异步