Zum Inhalt

_

Postman CLI (Newman) Cheatsheet

• Installation

Platform Command
npm (Global) INLINE_CODE_15
npm (Project) INLINE_CODE_16
yarn (Global) INLINE_CODE_17
Ubuntu/Debian INLINE_CODE_18____HTML_TAG_93____INLINE_CODE_19____HTML_TAG_94____INLINE_CODE_20
RHEL/CentOS/Fedora INLINE_CODE_21____HTML_TAG_95____INLINE_CODE_22
macOS (Homebrew) INLINE_CODE_23____HTML_TAG_96____INLINE_CODE_24
Windows (Chocolatey) INLINE_CODE_25____HTML_TAG_97____INLINE_CODE_26
Docker INLINE_CODE_27
Verify Installation INLINE_CODE_28

oder Grundlegende Befehle

Command Description
INLINE_CODE_29 Run a Postman collection from local file
INLINE_CODE_30 Run collection from URL (requires API key)
INLINE_CODE_31 Run collection with environment variables
INLINE_CODE_32 Run collection with global variables
INLINE_CODE_33 Run collection with 5 iterations
INLINE_CODE_34 Run with CSV data file (data-driven testing)
INLINE_CODE_35 Run with JSON data file
INLINE_CODE_36 Run specific folder from collection
INLINE_CODE_37 Add 2000ms delay between requests
INLINE_CODE_38 Set 10 second request timeout
INLINE_CODE_39 Disable SSL certificate verification
INLINE_CODE_40 Stop execution on first test failure
INLINE_CODE_41 Show detailed execution information
INLINE_CODE_42 Disable colored console output
INLINE_CODE_43 Always exit with code 0 (ignore failures)

/ Fortgeschrittene Nutzung

Command Description
INLINE_CODE_44 Use multiple reporters simultaneously
INLINE_CODE_45 Generate HTML report with custom filename
INLINE_CODE_46 Generate JUnit XML report for CI/CD
INLINE_CODE_47 Override environment variable via CLI
INLINE_CODE_48 Set global variable via CLI
INLINE_CODE_49 Export environment state after run
INLINE_CODE_50 Export global variables after run
INLINE_CODE_51 Export cookies after collection run
INLINE_CODE_52 Import cookies before collection run
INLINE_CODE_53 Use client SSL certificates
INLINE_CODE_54 Add custom CA certificates
INLINE_CODE_55 Set 5 second timeout for scripts
INLINE_CODE_56 Don't follow HTTP redirects
INLINE_CODE_57 Disable Unicode in output
INLINE_CODE_58 Set working directory for file operations
INLINE_CODE_59 Run using configuration file
INLINE_CODE_60 Run newman in Docker with volume mount

Konfiguration

Environment File Structure

{
  "id": "environment-id",
  "name": "Production Environment",
  "values": [
    {
      "key": "base_url",
      "value": "https://api.production.com",
      "enabled": true
    },
    {
      "key": "api_key",
      "value": "secret-key-123",
      "enabled": true,
      "type": "secret"
    },
    {
      "key": "timeout",
      "value": "5000",
      "enabled": true
    }
  ]
}

Global Variables File

{
  "id": "globals-id",
  "name": "Global Variables",
  "values": [
    {
      "key": "company_name",
      "value": "Acme Corp",
      "enabled": true
    },
    {
      "key": "api_version",
      "value": "v1",
      "enabled": true
    }
  ]
}

Newman Configuration File (newman.json)

{
  "collection": "collection.json",
  "environment": "environment.json",
  "globals": "globals.json",
  "iterationCount": 5,
  "delayRequest": 1000,
  "timeoutRequest": 10000,
  "reporters": ["cli", "html", "json"],
  "reporter": {
    "html": {
      "export": "./reports/report.html",
      "template": "./custom-template.hbs"
    },
    "json": {
      "export": "./reports/report.json"
    }
  },
  "bail": false,
  "insecure": false,
  "color": "on"
}

Datendatei für Iterationen (CSV)

username,password,expected_status
user1,pass123,200
user2,pass456,200
admin,admin789,200
invalid,wrong,401

Datendatei für Iterationen (JSON)

[
  {
    "username": "user1",
    "password": "pass123",
    "expected_status": 200
  },
  {
    "username": "user2",
    "password": "pass456",
    "expected_status": 200
  }
]

Reporter Optionen

# HTML Reporter with all options
newman run collection.json \
  -r html \
  --reporter-html-export ./reports/report.html \
  --reporter-html-template ./template.hbs \
  --reporter-html-title "API Test Report"

# JSON Reporter
newman run collection.json \
  -r json \
  --reporter-json-export ./reports/output.json

# JUnit Reporter
newman run collection.json \
  -r junit \
  --reporter-junit-export ./reports/junit.xml

# CLI Reporter (suppress specific outputs)
newman run collection.json \
  -r cli \
  --reporter-cli-no-summary \
  --reporter-cli-no-failures

Häufige Anwendungsfälle

Use Case 1: CI/CD Pipeline Integration

#!/bin/bash
# Jenkins/GitLab CI script for API testing

# Run collection with environment
newman run api-tests.json \
  -e production.json \
  -r cli,junit \
  --reporter-junit-export ./test-results/junit.xml \
  --bail \
  --suppress-exit-code

# Check exit code
if [ $? -eq 0 ]; then
  echo "All tests passed"
  exit 0
else
  echo "Tests failed"
  exit 1
fi

Use Case 2: Data-Driven Testing

# Test multiple user scenarios from CSV
newman run user-registration.json \
  -d user-data.csv \
  -e staging.json \
  -r html,cli \
  --reporter-html-export ./reports/registration-tests.html \
  --delay-request 500 \
  --timeout-request 15000

Use Case 3: Multi-Environment Testing

#!/bin/bash
# Test across multiple environments

ENVIRONMENTS=("dev" "staging" "production")

for env in "${ENVIRONMENTS[@]}"; do
  echo "Testing $env environment..."
  newman run collection.json \
    -e "environments/${env}.json" \
    -r html \
    --reporter-html-export "./reports/${env}-report.html" \
    --bail

  if [ $? -ne 0 ]; then
    echo "Tests failed in $env environment"
    exit 1
  fi
done

echo "All environments tested successfully"

Use Case 4: Scheduled API Monitoring

#!/bin/bash
# Cron job for API health monitoring (run every 15 minutes)
# */15 * * * * /path/to/api-monitor.sh

DATE=$(date +%Y%m%d-%H%M%S)

newman run health-check.json \
  -e production.json \
  -r json,html \
  --reporter-json-export "./logs/health-${DATE}.json" \
  --reporter-html-export "./logs/health-${DATE}.html" \
  --timeout-request 5000 \
  --suppress-exit-code

# Send alert if tests fail
if [ $? -ne 0 ]; then
  echo "API health check failed at ${DATE}" | mail -s "API Alert" admin@example.com
fi

Use Case 5: Programmatic Execution (Node.js)

// test-runner.js
const newman = require('newman');

newman.run({
    collection: require('./collection.json'),
    environment: require('./environment.json'),
    reporters: ['cli', 'html', 'json'],
    reporter: {
        html: {
            export: './reports/report.html'
        },
        json: {
            export: './reports/report.json'
        }
    },
    iterationCount: 3,
    delayRequest: 500,
    timeout: 10000
}, function (err, summary) {
    if (err) { 
        console.error('Collection run failed:', err);
        process.exit(1);
    }

    console.log('Collection run complete!');
    console.log('Total requests:', summary.run.stats.requests.total);
    console.log('Failed requests:', summary.run.stats.requests.failed);
    console.log('Test failures:', summary.run.stats.tests.failed);

    // Exit with error code if tests failed
    if (summary.run.stats.tests.failed > 0) {
        process.exit(1);
    }
});

oder Best Practices

  • **Use Environment Variables*: Speichern Sie sensible Daten (API-Tasten, Passwörter) in Umgebungsdateien, nie Hardcode in Sammlungen
  • **Implementieren Sie Proper Timeouts*: Stellen Sie realistische --timeout-request Werte basierend auf den erwarteten Reaktionszeiten Ihrer API fest, um Fehlausfälle zu vermeiden
  • **Einzelbericht aktivieren*: Verwenden Sie mehrere Reporter (-r cli,html,junit) für umfassende Testergebnisse und CI/CD-Integration
  • **Version Control Your Collections*: Export von Sammlungen von Postman und Store in Git neben Ihrer Codebase für das Versionstracking
  • ** Verwenden Sie Datendateien für Skalierbarkeit*: Speichern von CSV/JSON-Datendateien mit -d-Flag zum Testen mehrerer Szenarien ohne Duplikate
  • **Implementieren Retry Logic*: Für flaky-Tests wickeln Sie Newman-Befehle in Retry-Loops oder verwenden Sie CI/CD-Retry-Mechanismen
  • ** Kollektionen nach Zweck*: Separate Rauchtests, Regressionstests und Integrationstests in unterschiedliche Sammlungen zur gezielten Ausführung
  • **Export- und Archive-Ergebnisse*: Verwenden Sie immer --export-environment und --export-globals_, um Laufzeitzustand für Debugging zu erfassen
  • **Secure SSL-Zertifikate*: Verwenden __INLINE_CODE_66_ und --ssl-client-key_ für authentifizierte API-Tests, vermeiden --insecure_ in der Produktion
  • Monitor Performance: Verfolgen Sie die Ausführungszeiten in Berichten, um langsame Endpunkte und einen möglichen Leistungsabbau zu identifizieren

Fehlerbehebung

Issue Solution
"newman: command not found" Ensure Node.js is installed and newman is in PATH: INLINE_CODE_69 or use full path INLINE_CODE_70
SSL certificate verification failures Use INLINE_CODE_71 flag for self-signed certificates or add CA bundle with INLINE_CODE_72
Request timeouts in CI/CD Increase timeout with INLINE_CODE_73 (30 seconds) or check network connectivity in CI environment
Environment variables not loading Verify JSON structure matches Postman format, ensure INLINE_CODE_74 for all variables, check file path is correct
Collection runs but no output Specify reporter explicitly: INLINE_CODE_75 or check if output is redirected. Use INLINE_CODE_76 for detailed logging
"Cannot find module" errors Install newman locally in project: INLINE_CODE_77 or verify global installation: INLINE_CODE_78
Tests pass in Postman but fail in newman Check for timing issues, add INLINE_CODE_79, verify environment variables are properly exported
Memory issues with large collections Run collections in smaller batches using INLINE_CODE_80 flag or increase Node.js memory: INLINE_CODE_81
Docker volume mount issues Use absolute paths: INLINE_CODE_82
Exit code always 0 despite failures Remove INLINE_CODE_83 flag or check CI/CD script isn't ignoring exit codes with INLINE_CODE_84
Reporter files not generated Ensure output directory exists, check write permissions, use absolute paths for INLINE_CODE_85 options
Data file iterations not working Verify CSV/JSON format matches expected structure, ensure INLINE_CODE_86 flag points to correct file, check for encoding issues

Weitere Ressourcen

Ausführen von Sammlungen von Postman

# Using Postman API to export collection
curl -X GET \
  'https://api.getpostman.com/collections/<collection-uid>' \
  -H 'X-Api-Key: <your-postman-api-key>' \
  -o collection.json

# Run exported collection
newman run collection.json

Neue Reporter installieren

# HTML reporter (included by default)
npm install -g newman-reporter-html

# HTMLExtra reporter (enhanced HTML reports)
npm install -g newman-reporter-htmlextra

# Confluence reporter
npm install -g newman-reporter-confluence

# Slack reporter
npm install -g newman-reporter-slack

# TeamCity reporter
npm install -g newman-reporter-teamcity

Benutzerdefinierte Reporter verwenden

# Run with custom reporter
newman run collection.json -r htmlextra

# HTMLExtra with options
newman run collection.json \
  -r htmlextra \
  --reporter-htmlextra-export ./report.html \
  --reporter-htmlextra-darkTheme \
  --reporter-htmlextra-title "Custom API Tests"

Parallel Execution Pattern

# Using GNU Parallel for concurrent execution
parallel -j 4 newman run ::: \
  auth-tests.json \
  user-tests.json \
  order-tests.json \
  payment-tests.json

# Using background jobs
newman run collection1.json -e env1.json & \
newman run collection2.json -e env2.json & \
newman run collection3.json -e env3.json & \
wait

echo "All collections completed"