FastAPI 通过 TestClient 在获取请求中传递 json

FastAPI passing json in get request via TestClient

我正在尝试测试我用 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)

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

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())

当我 运行 调试代码时,我意识到没有达到 get 方法中的断点。当我将请求类型更改为 post 时,一切正常。

我做错了什么?

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

或者,您可以 POST 向您的服务器发出搜索请求。 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())

这将允许从 url mydomain 获取请求。com/webrecord/check_if_object_exist/{对象的键}。

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