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?
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 (eg 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).
@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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.