0
0
PyTesttesting~5 mins

API client testing in PyTest

Choose your learning style9 modes available
Introduction

API client testing helps check if your program talks correctly with other software through APIs. It makes sure your requests and responses work as expected.

When you want to verify that your API calls return the right data.
When you need to check how your client handles errors from the API.
When you update your API client code and want to confirm it still works.
When you want to automate testing of API endpoints without manual checks.
Syntax
PyTest
def test_api_client():
    response = client.get('/endpoint')
    assert response.status_code == 200
    assert response.json() == expected_data

Use assert to check if the API response matches what you expect.

Use a test client or mock to simulate API calls in tests.

Examples
Test that getting user with ID 1 returns status 200 and includes a username.
PyTest
def test_get_user(client):
    response = client.get('/users/1')
    assert response.status_code == 200
    assert 'username' in response.json()
Test creating a new item with POST and check the response data.
PyTest
def test_post_create_item(client):
    data = {'name': 'item1'}
    response = client.post('/items', json=data)
    assert response.status_code == 201
    assert response.json()['name'] == 'item1'
Test that requesting an unknown endpoint returns 404 error.
PyTest
def test_handle_404(client):
    response = client.get('/unknown')
    assert response.status_code == 404
Sample Program

This test script uses a fake client to simulate API calls. It tests a successful user fetch and a 404 error for unknown URL.

PyTest
import pytest

class FakeClient:
    def get(self, url):
        if url == '/users/1':
            return FakeResponse(200, {'username': 'alice'})
        return FakeResponse(404, {})

class FakeResponse:
    def __init__(self, status_code, json_data):
        self.status_code = status_code
        self._json = json_data
    def json(self):
        return self._json

@pytest.fixture
def client():
    return FakeClient()

def test_get_user(client):
    response = client.get('/users/1')
    assert response.status_code == 200
    assert 'username' in response.json()

def test_handle_404(client):
    response = client.get('/unknown')
    assert response.status_code == 404
OutputSuccess
Important Notes

Use fixtures in pytest to create reusable API clients for tests.

Mock external API calls to avoid real network requests during testing.

Check both status codes and response data for thorough testing.

Summary

API client testing checks if your code correctly sends requests and handles responses.

Use assertions to verify status codes and response content.

Mock or fake clients help test without real API calls.