API Navigator Logo

Python Unit Test API with unittest

Author: Newtum

This example shows how to write a simple unit test for an API endpoint using Python's built-in `unittest` framework and the `requests` library. We'll use mocking to avoid making real network calls.

Writing a Test Case

We use `unittest.mock.patch` to replace `requests.get` with a mock object. This allows us to simulate an API response and test our function's logic in isolation.

import unittest
from unittest.mock import Mock, patch
import requests

# A simple function that interacts with an API
def get_user_data(user_id):
    response = requests.get(f"https://api.example.com/users/{user_id}")
    response.raise_for_status()
    return response.json()

class TestApi(unittest.TestCase):

    @patch('requests.get')
    def test_get_user_data_success(self, mock_get):
        # Configure the mock to return a successful response
        mock_response = Mock()
        mock_response.status_code = 200
        mock_response.json.return_value = {'id': 1, 'name': 'John Doe'}
        mock_get.return_value = mock_response

        # Call the function
        user_data = get_user_data(1)

        # Assert that the function behaved as expected
        self.assertEqual(user_data, {'id': 1, 'name': 'John Doe'})
        mock_get.assert_called_once_with("https://api.example.com/users/1")

# To run this, you would save it as a Python file and run 'python -m unittest your_file.py'
print("This code demonstrates a unittest test case for an API call.")
print("The test passes if run in a unittest context.")