Testing Flask REST API using Flask client

Privalov Vladimir
1 min readApr 5, 2021

--

You can easily test your REST API using Flask client. To access Flask test client use method test_client() on your app module:

from app import appclient = app.test_client()

Flask test client allows to work with it through context manager using operator with.

Send GET query

with app.test_client() as c:
rv = c.get('/users', json={})
print(rv.data)
print('status: ', rv.status_code)

We can get JSON from response:

json_data = rv.get_json()

Let’s send POST query with some parameters:

with app.test_client() as c:
rv = c.post('/auth/signin/local', json={
'email': '<some email>', 'password': '<some password>'
}
print(rv.data)
print('status: ' , rv.status_code)

Send PUT query:

token = <some token>
with app.test_client() as c:
rv = c.put('/auth/verify-email', json={
'token': token
})
print(rv.data)
print('status: ' , rv.status_code)

Send DELETE query

with app.test_client() as c:
rv = c.delete('/users/%s' % id, json={}, headers=headers)
print(rv.data)
print('status: ', rv.status_code)

Set authentication headers

token = <some token>
authorization = 'Bearer ' + str(token)

headers = {
'Content-Type': 'application/json',
'Authorization': authorization
}
with app.test_client() as c:
rv = c.put('/auth/password-update', json={
"current_password": "<some password>",
"new_password": "<some password>",
}, headers=headers)
print(rv.data)
print('status: ' , rv.status_code)

That’s it. Enjoy web development with Flask.

--

--

No responses yet