API Navigator Logo

Python API Testing with Postman (Introduction)

Author: Newtum

While this site is a Postman alternative, it's useful to know how to integrate Python with Postman workflows using its command-line runner, `newman`.

What is Postman and Newman?

Postman is a popular GUI tool for API testing. A Postman Collection is a group of saved requests. Newman is a command-line tool that allows you to run Postman Collections directly from your terminal, which is ideal for automation and CI/CD pipelines.

Automating with Python and Newman

You can use Python's `subprocess` module to execute a newman command, run a Postman collection, and capture the results.

import subprocess
import os

# You would first export your Postman Collection as a JSON file.
collection_file = 'my_api_tests.postman_collection.json'
environment_file = 'my_env.postman_environment.json' # Optional

# Check if newman is installed
try:
    subprocess.run(['newman', '--version'], check=True, capture_output=True)
except (subprocess.CalledProcessError, FileNotFoundError):
    print("Newman is not installed or not in the system's PATH.")
    print("Install it with: npm install -g newman")
else:
    print("Newman is found. Running the collection...")
    # This code assumes the collection file exists in the same directory.
    # We cannot execute this here, but this is the command you would run.
    command = [
        'newman', 'run', collection_file,
        '-e', environment_file,
        '--reporters', 'cli,html', # Generate CLI and HTML reports
        '--reporter-html-export', 'newman_report.html'
    ]
    
    print("Python would execute the following command:")
    print(' '.join(command))
    
    # In a real script:
    # result = subprocess.run(command, capture_output=True, text=True)
    # print("Newman execution finished.")
    # print("Exit Code:", result.returncode)
    # print("Output:", result.stdout)