Backend Development 11 min read

Python Output and Reporting Techniques for API Testing (Beginner to Advanced)

This guide presents beginner to advanced Python techniques for formatting and reporting API test results, covering print statements, logging, JSON, markdown tables, pytest reports, unittest with HTMLTestRunner, Allure, coverage analysis, data visualization, and Selenium‑wire network capture, with practical code examples and best‑practice notes.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Python Output and Reporting Techniques for API Testing (Beginner to Advanced)

Beginner Section

Basic output methods are introduced, starting with the print() function for quick debugging, followed by the logging module for production‑grade logs with configurable levels (DEBUG, INFO, WARNING, ERROR, CRITICAL). Structured JSON output is shown for sending test results to reporting systems, and table or Markdown formats are suggested for more readable test reports.

Usage Scenarios and Code Examples

1. Using print() and f‑strings – quick script debugging.

def test_api():
    response = requests.get('https://api.example.com/data')
    if response.status_code == 200:
        data = response.json()
        print(f"Response received successfully: {data['message']}")
    else:
        print(f"Failed to get response. Status Code: {response.status_code}")

2. Using the logging module – production logging.

import logging
logging.basicConfig(level=logging.INFO)

def test_api():
    response = requests.get('https://api.example.com/data')
    if response.status_code == 200:
        data = response.json()
        logging.info(f"Response received successfully: {data['message']}")
    else:
        logging.error(f"Failed to get response. Status Code: {response.status_code}")

3. JSON formatted output – structured data for downstream processing.

import json

def test_api():
    response = requests.get('https://api.example.com/data')
    result = {
        'status': 'success' if response.status_code == 200 else 'failure',
        'message': response.json()['message'] if response.status_code == 200 else 'Failed to get response',
        'http_status': response.status_code
    }
    print(json.dumps(result, indent=2))

4. Table or Markdown output – human‑readable test reports.

def test_api():
    response = requests.get('https://api.example.com/data')
    status = 'Success' if response.status_code == 200 else 'Failure'
    message = response.json().get('message', 'No message') if response.status_code == 200 else 'Failed to get response'
    http_status = response.status_code
    print(f"| Test Case | Status | Message | HTTP Status |\n| --- | --- | --- | --- |\n| API Test | {status} | {message} | {http_status} |")

Important Notes

Avoid DEBUG level logs in production to prevent leaking sensitive data.

Ensure all variables are defined before formatting to avoid NoneType errors.

Large volumes of logging can affect performance; adjust strategies accordingly.

Never expose passwords or keys in logs or output.

Standardize output formats across the team for maintainability.

Intermediate Section

Further examples demonstrate JSON output, Markdown tables, and pytest HTML reports, each with concise code snippets and usage tips.

# JSON output example
import json, requests

def test_api():
    response = requests.get('https://api.example.com/data')
    result = {
        'status': 'success' if response.status_code == 200 else 'failure',
        'message': response.json().get('message', 'No message'),
        'http_status': response.status_code
    }
    print(json.dumps(result, indent=2))

test_api()
# Markdown table output example
import requests

def test_api():
    response = requests.get('https://api.example.com/data')
    status = 'Success' if response.status_code == 200 else 'Failure'
    message = response.json().get('message', 'No message')
    http_status = response.status_code
    print('| Test Case | Status | Message | HTTP Status |')
    print('| --------- | ------ | ------- | ----------- |')
    print(f'| API Test  | {status} | {message} | {http_status} |')

test_api()
# pytest HTML report example (requires pytest-html)
# Run: pytest --html=test_report.html

Advanced Section

More sophisticated reporting techniques are covered, including unittest with HTMLTestRunner, Allure reports, coverage analysis with pytest‑cov, data visualization using pandas and matplotlib, and network request capture with Selenium‑wire.

import unittest
from HTMLTestRunner import HTMLTestRunner

class TestExampleAPI(unittest.TestCase):
    def test_api_response(self):
        response = requests.get('https://api.example.com/data')
        self.assertEqual(response.status_code, 200, "Expected status code 200")

if __name__ == '__main__':
    suite = unittest.TestLoader().loadTestsFromTestCase(TestExampleAPI)
    with open("test_report.html", "w") as f:
        runner = HTMLTestRunner(stream=f, title='API Test Report', description='This demonstrates the report output by HTMLTestRunner.')
        runner.run(suite)
import allure, pytest

@allure.feature("API Feature")
class TestExampleAPI:
    @allure.story("API Response")
    def test_api_response(self):
        response = requests.get('https://api.example.com/data')
        with allure.step("Check the status code"):
            assert response.status_code == 200, "Expected status code 200"

if __name__ == '__main__':
    pytest.main(['-s', '--alluredir=allure-results'])
    # Then run: allure serve allure-results
# pytest‑cov coverage example

def test_function():
    # test logic here
    pass

if __name__ == '__main__':
    pytest.main(['--cov=.', '--cov-report=html'])
# Data visualization with pandas and matplotlib
import pandas as pd
import matplotlib.pyplot as plt

data = {'test_name': ['test1', 'test2', 'test3'], 'status': ['passed', 'failed', 'passed']}
df = pd.DataFrame(data)
result_counts = df['status'].value_counts()
result_counts.plot(kind='bar')
plt.title('Test Results')
plt.xlabel('Status')
plt.ylabel('Count')
plt.show()
# Selenium‑wire network capture example
from selenium.webdriver.common.by import By
from seleniumwire import webdriver

driver = webdriver.Chrome(seleniumwire_options=dict())
driver.get('https://www.example.com')
requests = driver.requests
for request in requests:
    if request.response:
        print(request.path, request.response.status_code, request.response.headers['Content-Type'])

These advanced methods help you generate clearer, more detailed test reports and gain deeper insight into test execution, improving transparency and traceability.

PythonautomationTestingJSONloggingpytestreporting
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.