Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FastAPI passing json in get request via TestClient

Tags:

python

fastapi

I'm try to test the api I wrote with Fastapi. I have the following method in my router :

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

and the following test in my test file :

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

When I run the code in debug I realized that the break points inside the get method aren't reached. When I changed the type of the request to post everything worked fine.

What am I doing wrong?

like image 382
JeyJ Avatar asked Apr 30 '26 10:04

JeyJ


1 Answers

In order to send data to the server via a GET request, you'll have to encode it in the url, as GET does not have any body. This is not advisable if you need a particular format (e.g. JSON), since you'll have to parse the url, decode the parameters and convert them into JSON.

Alternatively, you may POST a search request to your server. A POST request allows a body which may be of different formats (including JSON).

If you still want GET request

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

This will allow to GET requests from url mydomain.com/webrecord/check_if_object_exist/{the key of the object}.

One final note: I made all the parameters mandatory. You may change them by declaring to be None by default. See fastapi Docs

like image 77
lsabi Avatar answered May 02 '26 23:05

lsabi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!