FastAPI passing json in get request via TestClient

2024/11/17 10:04:23

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.keyreturn 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 == 200assert 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?

Answer

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.keyreturn 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 == 200assert 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

https://en.xdnf.cn/q/71236.html

Related Q&A

Python TDD directory structure

Is there a particular directory structure used for TDD in Python?Tutorials talk about the content of the tests, but not where to place themFrom poking around Python Koans, suspect its something like:/…

Pillow was built without XCB support

Im working on a program that uses ImageGrab in Pillow. I am getting the error mentioned in the title. I notice in the documentation that it says the generic pip install Pillow doesnt come with libxcb. …

Set equal aspect in plot with colorbar

I need to generate a plot with equal aspect in both axis and a colorbar to the right. Ive tried setting aspect=auto, aspect=1, and aspect=equal with no good results. See below for examples and the MWE.…

How to emit dataChanged in PyQt5

The code below breaks on self.emit line. It works fine in PyQt4. How to fix this code so it works in PyQt5?from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtCore import QObject, pyqtSignalclass …

django: gettext and coercing to unicode

I have following code in my django application.class Status(object):def __init__(self, id, desc):self.id = idself.desc = descdef __unicode__(self):return self.descSTATUS = Status(0, _(u"Some text&…

Telegram bot api keyboard

I have problem with Telegram Bot Api and with "ReplyKeyboard". Im using Python 2.7 and I send post request:TelegramAPI.post(TELEGRAM_URL + "sendMessage", data=dict(chat_id=CHAT_ID, …

Use of torch.stack()

t1 = torch.tensor([1,2,3]) t2 = torch.tensor([4,5,6]) t3 = torch.tensor([7,8,9])torch.stack((t1,t2,t3),dim=1)When implementing the torch.stack(), I cant understand how stacking is done for different di…

Is it possible to sort a list with reduce?

I was given this as an exercise. I could of course sort a list by using sorted() or other ways from Python Standard Library, but I cant in this case. I think Im only supposed to use reduce().from funct…

Flask-WTF set time limit on CSRF token

Im currently using Flask-WTF v0.13.1, i have a few forms on my website, all created including the CSRF token.For some reasons i have to set a different expiration on each form, so far i could set manua…

Extracting Intermediate layer outputs of a CNN in PyTorch

I am using a Resnet18 model. ResNet((conv1): Conv2d(3, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False)(bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats…