FastAPI 通过 TestClient 在 get 请求中传递 json

Jey*_*eyJ 8 python fastapi

我正在尝试测试我用 Fastapi 编写的 api。我的路由器中有以下方法:

@app.get('/webrecord/check_if_object_exist')
async def check_if_object_exist(payload: WebRecord) -> bool:
    key = get_key_of_obj(payload.data) if payload.key is None else payload.key
    return await check_if_key_exist(key)
Run Code Online (Sandbox Code Playgroud)

以及我的测试文件中的以下测试:

client = TestClient(app)
class ServiceTest(unittest.TestCase):
.....
    def test_check_if_object_is_exist(self):
        webrecord_json = {'a':1}
        response = client.get("/webrecord/check_if_object_exist", json=webrecord_json)
        assert response.status_code == 200
        assert response.json(), "webrecord should already be in db, expected : True, got : {}".format(response.json())
Run Code Online (Sandbox Code Playgroud)

当我在调试中运行代码时,我意识到未到达 get 方法内的断点。当我更改发布请求的类型时,一切正常。

我究竟做错了什么?

lsa*_*abi 5

为了通过 GET 请求将数据发送到服务器,您必须在 url 中对其进行编码,因为 GET 没有任何正文。如果您需要特定格式(例如 JSON),则不建议这样做,因为您必须解析 url、解码参数并将它们转换为 JSON。

或者,您可以将搜索请求发布到您的服务器。POST 请求允许主体采用不同的格式(包括 JSON)。

如果您仍然想要 GET 请求

    @app.get('/webrecord/check_if_object_exist/{key}')
async def check_if_object_exist(key: str, data: str) -> bool:
    key = get_key_of_obj(payload.data) if payload.key is None else payload.key
    return await check_if_key_exist(key)


client = TestClient(app)
class ServiceTest(unittest.TestCase):
.....
    def test_check_if_object_is_exist(self):
        response = client.get("/webrecord/check_if_object_exist/key", params={"data": "my_data")
        assert response.status_code == 200
        assert response.json(), "webrecord should already be in db, expected : True, got : {}".format(response.json())
Run Code Online (Sandbox Code Playgroud)

这将允许从 url mydomain.com/webrecord/check_if_object_exist/{the key of the object} 获取请求。

最后一点:我将所有参数设为强制。None您可以通过声明默认来更改它们。请参阅fastapi 文档