Complete Guide on API Integration Testing (Out-of-box Code Available)

API integration testing ensures that different APIs work together as expected. This testing validates how various components interact, including:

  • API authentication

  • Pagination

  • Rate limiting

  • Response bodies

Pro tip: For seamless API integration testing, Apidog is your go-to platform. It simplifies the process of simulating real-world workflows, enabling you to efficiently test how multiple APIs interact.

Key Benefits of API Integration Testing

  1. Reliability & Data Accuracy: Ensures data is transferred correctly between systems and that APIs work reliably.

  2. Error Handling: Helps identify and address errors, improving how the system reacts to problematic API responses.

  3. Performance Optimization: Helps spot performance bottlenecks, especially in handling large amounts of data.

  4. Compatibility Maintenance: Ensures new API updates do not break the system.

  5. Security: Helps detect vulnerabilities and safeguard data exchanges.

API Integration Testing vs Unit Testing

  • Unit Testing: Tests individual components or functions in isolation.

  • Integration Testing: Tests how different components (including APIs) work together. It verifies that the integration of APIs works as a whole.

Key Steps in API Integration Testing

  1. Develop a Testing Plan: Outline the goals and scenarios to be tested.

  2. Create Test Cases: Build different cases to cover various use cases.

  3. Run Tests: Execute the integration tests.

  4. Track, Report, and Resolve Issues: Identify issues from tests, resolve them, and track progress.

  5. Retest: Ensure that any fixes resolve the problem without introducing new ones.

  6. Repeat: Continuously improve the integration until it’s free of bugs.

API Integration Testing Using Apidog

Apidog significantly streamlines API integration testing by enabling QA engineers to design and execute complex test scenarios that simulate real-world workflows involving multiple APIs.

For instance, in a pet purchase process, where various APIs interact—such as browsing pet lists, adding items to a cart, placing an order, making payments, and querying order details—Apidog makes it easy to set up these interconnected tests.

using Apidog for API integration testing

QA engineers can create scenarios by linking API endpoints and transferring data between them, such as passing an order ID between the "Create Order" and subsequent payment and order query endpoints. Apidog’s robust data handling allows this either by saving the order ID as a variable or by directly referencing the return value from the previous step, streamlining the testing process.

data-transferring-between-apis

For more complex operations, such as bulk actions like adding multiple pets to a cart, Apidog’s ForEach loop simplifies the task by automatically inserting the pet IDs from an array into each API request.

Apidog ForEach loop for API integration testing

Once the test scenarios are created and executed, Apidog generates detailed test reports, which help QA engineers quickly identify and fix issues, ensuring that all APIs function correctly within a unified workflow.

api-integration-report-generated-by-apidog

With Apidog’s integration testing capabilities, developers can efficiently simulate real user actions, test multiple endpoints together, and ensure seamless data exchanges across APIs, making it the go-to platform for API development, testing, and integration.

Learn how Apidog enhances API testing and improve testing efficiency for QA engineers.

Best Practices for API Integration Testing

  1. Use Mocking Libraries: Use libraries like requests_mock to simulate network interactions. This isolates the test and speeds up testing by avoiding real API calls.

  2. Error Handling: Test how your system responds to various API errors (e.g., 404, 500) to ensure it doesn’t break.

  3. Test Boundary Values: Use extreme values to test how the system handles them.

  4. Backward Compatibility: Ensure that API changes don’t break your existing functionality.

  5. Realistic Data: Use realistic scenarios (e.g., real user data, accurate pricing) to test how the system will behave in the real world.

  6. Keep Tests Updated: As APIs evolve, update your tests to remain accurate and reliable.

Example of API Integration Testing

Here’s a practical example of testing API integration using Python and the requests_mock library.

Step 1: Install Required Libraries

pip install requests requests_mock

Step 2: API Integration Code Example

This example demonstrates how to integrate two public APIs: one for currency conversion and one for checking product availability based on a zip code.

import requests

def get_converted_price(product_price: int, conversion_currency: str) -> float:
    converted_price = None
    base_currency = "usd"
    api_url = f"https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/latest/currencies/{base_currency}/{conversion_currency.lower()}.json"

    try:
        resp = requests.get(api_url)
        if resp.ok:
            currency_data = resp.json()
            converted_price = product_price * currency_data[conversion_currency]
            print(f"Converted price: {round(converted_price, 2)} {conversion_currency.upper()}")
        else:
            print(f"Error: {resp.text}")
    except Exception as ex:
        print(f"Exception: {ex}")
    finally:
        return converted_price

def get_product_availability(zipcode: int) -> bool:
    availability = None
    api_url = f"https://api.zippopotam.us/us/{zipcode}"

    try:
        resp = requests.get(api_url)
        if resp.ok:
            zip_data = resp.json()
            state = zip_data["places"][0]["state"]
            availability = False if state in ["Texas", "California"] else True
            print(f"Availability in {state}: {availability}")
        else:
            print(f"Error: {resp.text}")
    except Exception as ex:
        print(f"Exception: {ex}")
    finally:
        return availability

Step 3: Test API Integrations

You can create unit tests to validate the integration using unittest and requests_mock:

import unittest
import requests_mock
from api_integration import get_converted_price, get_product_availability

class TestAPIIntegrations(unittest.TestCase):

    def test_get_converted_price(self):
        test_data = {"usd": 82.6}
        expected_price = 8260
        with requests_mock.Mocker() as mock:
            mock.get("https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/latest/currencies/usd/inr.json", json=test_data)
            calculated_price = get_converted_price(100, "inr")
            self.assertEqual(calculated_price, expected_price)

    def test_get_converted_price_failure(self):
        with requests_mock.Mocker() as mock:
            mock.get("https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/latest/currencies/usd/inr.json", status_code=404)
            calculated_price = get_converted_price(100, "inr")
            self.assertIsNone(calculated_price)

    def test_get_product_availability_true(self):
        test_data = {"places": [{"state": "California"}]}
        with requests_mock.Mocker() as mock:
            mock.get("https://api.zippopotam.us/us/90210", json=test_data)
            availability = get_product_availability(90210)
            self.assertTrue(availability)

    def test_get_product_availability_false(self):
        test_data = {"places": [{"state": "Texas"}]}
        with requests_mock.Mocker() as mock:
            mock.get("https://api.zippopotam.us/us/75001", json=test_data)
            availability = get_product_availability(75001)
            self.assertFalse(availability)

    def test_get_product_availability_failure(self):
        with requests_mock.Mocker() as mock:
            mock.get("https://api.zippopotam.us/us/75001", status_code=500)
            availability = get_product_availability(75001)
            self.assertIsNone(availability)

if __name__ == '__main__':
    unittest.main(verbosity=2)

Step 4: Run the API Integration Tests

To run the tests, use the following command in your terminal:

python api_integration_tests.py

This will execute all the tests and show a detailed output of each one, including whether the mock API responses were correctly handled and if the expected results were met.

Final Thoughts

API integration testing ensures that APIs are functioning together as intended. By using mocking libraries and comprehensive test cases, you can efficiently verify your system's integration behavior. Always ensure your tests are updated as your APIs evolve, and consider implementing automated tests for continuous integration.

If you're looking to automate the integration process further, tools like Apidog offer a unified API for quickly scaling and testing integrations.