使用多个参数的 GET 请求

GET request that uses more than one parameter

如果我用这样的 GET 操作构建一个简单的 FastAPI 实例:

from fastapi import FastAPI

app = FastAPI()

@app.get("/users/{id_user}")
async def double(id_user: int):
    return {"result": id_user * 2}

if __name__ == "__main__":
    uvicorn.run(app, host="127.0.0.1", port=8000)

如果我 运行 API 然后我立即使用

r = requests.get("http://127.0.0.1:8000/users/8")
print(r.json())

我答对了

{"result": 16}

现在我想做这样的事情:

@app.get("/users/{id_user}")
async def multiplication(id_user: int, k: int):
    return {"result": id_user * k}

requests.get() 怎样写才能得到想要的结果?

你应该对两个参数做这样的事情

来自https://fastapi.tiangolo.com/tutorial/query-params/

@app.get("/multiplication/")
async def multiplication(base: int = 0, times: int = 10):
    return {'response': base * times}

查询是在 ? 之后的一组键值对。在 URL 中,由 & 字符分隔。

例如,在URL中你将发送参数

http://127.0.0.1:8000/items/?base=0&times=10