API Navigator Logo

Python REST API Integration Test Example

Author: Newtum

This example demonstrates a simple integration test for a REST API using Python. Unlike unit tests, integration tests make real calls to a live API endpoint (often in a test or staging environment) to verify its behavior.

Writing an Integration Test

The test makes a `GET` request to a public API and asserts that the response has a `200 OK` status code and that the returned data has the expected structure (e.g., contains certain keys).

import requests
import unittest

class TestJsonPlaceholderApi(unittest.TestCase):

    BASE_URL = 'https://jsonplaceholder.typicode.com'

    def test_get_single_post(self):
        """
        Tests fetching a single post and validating the response.
        """
        response = requests.get(f"{self.BASE_URL}/posts/1")

        # 1. Assert the status code is 200 OK
        self.assertEqual(response.status_code, 200)

        # 2. Parse the JSON and assert it's a dictionary
        post_data = response.json()
        self.assertIsInstance(post_data, dict)

        # 3. Assert that essential keys are in the response
        self.assertIn('userId', post_data)
        self.assertIn('id', post_data)
        self.assertIn('title', post_data)
        self.assertIn('body', post_data)

        # 4. Assert a specific value
        self.assertEqual(post_data['id'], 1)

# To run, save and execute 'python -m unittest your_test_file.py'
print("This code shows an integration test case.")
print("Running it would make a live API call to jsonplaceholder.")