Kokil Thapa - Professional Web Developer in Nepal
Freelancer Web Developer in Nepal with 15+ Years of Experience

Kokil Thapa is an experienced full-stack web developer focused on building fast, secure, and scalable web applications. He helps businesses and individuals create SEO-friendly, user-focused digital platforms designed for long-term growth.

API Testing Automation with Postman and Newman

By Kokil Thapa | Last reviewed: September 2026

Manual API checks die the moment you ship a second endpoint. API Testing Automation with Postman and Newman solves that by turning your Postman collection into a repeatable test suite you can run locally and in CI. You design requests once, add JavaScript assertions in the Tests tab, then invoke Newman—the Postman CLI runner—to execute the same flows on every push. For teams shipping Laravel API best practices or third-party integrations, that shift from ad-hoc clicks to pipeline gates is often the difference between catching a broken auth header before deploy and debugging it in production at midnight.

What is API Testing Automation with Postman and Newman?

Postman is the authoring layer. Newman is the execution engine. Together they form a practical automation stack that does not require rewriting every endpoint test in PHPUnit or Jest unless you want to.

In practice, you group related HTTP calls into a collection: login, create resource, list resource, delete resource. Each request carries pre-request scripts (token refresh, timestamp headers) and test scripts (assert status, parse JSON, chain IDs into the next call). Newman reads that exported JSON and runs it headlessly—perfect for GitLab CI, GitHub Actions, or a cron job against staging.

Postman + Newman Automation FlowPostmanDesign + scriptsCollectionJSON exportNewman CLIHeadless runCI PipelineGitLab / ActionsEach request runs assertionsStatus codes, JSON fields, response timeEnvironment vars: baseUrl, token, tenantIdJUnit / HTML reporters for merge gatesFail build on regression
API Testing Automation with Postman and Newman: design in Postman, export JSON, run Newman in CI with assertions and reports.

This pattern fits REST API development projects where product owners still want a visual collection for demos, but engineering needs automated gates. I've used it on production Laravel applications alongside PHPUnit feature tests—the Postman layer often covers cross-service smoke paths that span auth, webhooks, and payment callbacks faster than spinning up full browser tests.

Newman is maintained by Postman and published on npm. Install it globally or as a dev dependency alongside Node.js 26 LTS. Composer 2.10 and PHP 8.3+ still matter because your API under test likely runs on Laravel 12 or 13—but Newman itself is a Node tool, not a PHP one.

How do you build a Postman collection for repeatable API tests?

Start with one folder per user journey, not one folder per HTTP verb. A booking API folder might contain: authenticate, create booking, fetch booking, cancel booking. Each step stores IDs in collection or environment variables for the next request.

Organise folders around business flows

Name folders after workflows your stakeholders understand. "Checkout with Khalti callback" beats "POST /api/v1/payments". On client projects with Laravel booking systems, flow-based folders make handoff easier when someone else maintains the suite six months later.

Write test scripts that assert behaviour, not luck

The Tests tab runs after each response. Use pm.test for readable output and pm.expect for Chai-style assertions. Validate status, content type, required fields, and error shapes—not just 200 OK.

pm.test("Status is 201 Created", function () {
    pm.response.to.have.status(201);
});

const body = pm.response.json();
pm.test("Booking has id and status", function () {
    pm.expect(body.data).to.have.property("id");
    pm.expect(body.data.status).to.eql("pending");
});

pm.collectionVariables.set("bookingId", body.data.id);

Paste sample JSON into the JSON formatter when debugging malformed responses locally. For regex-heavy payload checks, pair Postman tests with a quick pattern in the regex tester before you commit the script.

Chain variables across requests

Store tokens and entity IDs at the right scope:

  • Environment variables — baseUrl, apiKey, staging vs production flags.
  • Collection variables — shared defaults checked into Git with sanitized placeholders.
  • Local variables — ephemeral values inside a single request script.

Never commit live secrets. Use CI masked variables and reference them as {{apiToken}} in Postman, injected at runtime via Newman --env-var flags.

Postman Collection StructureCollection: Booking API v1Folder: AuthLogin, refresh tokenFolder: BookingsCRUD + cancel flowFolder: PaymentsGateway callbacksEach request: Pre-request script + Tests tab assertionsEnvironment: baseUrl, bearerToken, bookingIdStaging and production as separate env files
Structure Postman collections by business flow, with test scripts and environment variables feeding Newman runs.

Export both files to version control:

  1. Collection → Export → Collection v2.1 JSON → postman/collection.json
  2. Environment → Export → postman/staging.environment.json
  3. Add an npm script so every developer runs the same command.
{
  "scripts": {
    "test:api": "newman run postman/collection.json -e postman/staging.environment.json --reporters cli,junit --reporter-junit-export reports/newman.xml"
  },
  "devDependencies": {
    "newman": "^6.2.0"
  }
}

Pin Newman in package.json. npm 12 resolves it consistently across laptops and CI runners. See the official Newman CLI documentation for reporter options and exit codes.

How do you run Newman from the command line and in CI?

Local runs should mirror CI exactly. If developers only click Send in Postman GUI, drift appears fast—missing env vars, stale tokens, or tests that pass only in GUI cache state.

Command-line essentials

npm ci
npx newman run postman/collection.json \
  -e postman/staging.environment.json \
  --env-var "apiToken=$API_TOKEN" \
  --bail \
  --timeout-request 15000 \
  --reporters cli,junit \
  --reporter-junit-export reports/newman.xml

--bail stops on first failure—useful for fast feedback. Omit it when you want a full failure report before fixing. --timeout-request prevents hung third-party callbacks from blocking the pipeline for minutes.

GitLab CI job example

On sister sites I maintain with Deployer 7 and GitLab CI, API smoke tests run after deploy to staging—not before unit tests, but before promoting to production. The job hits a live staging URL with read-only and sandbox credentials.

api_smoke_newman:
  stage: test
  image: node:26-bookworm
  script:
    - npm ci
    - npx newman run postman/collection.json
        -e postman/staging.environment.json
        --env-var "baseUrl=$STAGING_BASE_URL"
        --env-var "apiToken=$STAGING_API_TOKEN"
        --reporters cli,junit
        --reporter-junit-export reports/newman.xml
  artifacts:
    when: always
    reports:
      junit: reports/newman.xml
  rules:
    - if: $CI_COMMIT_BRANCH == "main"

This aligns with broader integration testing in CI pipelines and build pipeline automation practices. Newman exit code 1 fails the job; GitLab surfaces which assertion broke in the JUnit tab.

Newman in CI/CD PipelineGit pushBuild appDeploy stagingNewman smokeNewman executes collection against staging URLMasked CI variables inject secrets at runtimeJUnit artifact attached to pipeline jobPass: promoteFail: block release
Run Newman after staging deploy so automated API tests validate a real running environment before production promotion.

Schedule nightly Newman runs against production read-only endpoints if your SLA allows it. Rate-limit and use dedicated monitoring credentials—never a superadmin token. Pair results with API security checklist reviews so smoke tests do not accidentally expose sensitive data in CI logs.

How do you handle authentication and environments in automated API tests?

Auth is where API suites usually fail in CI first. A collection that works in Postman GUI often breaks headlessly because the login step never ran or the bearer token expired.

Laravel Sanctum and Passport patterns

For Laravel REST APIs, create a dedicated "Auth" folder whose sole job is obtaining a token. Store it with pm.environment.set("bearerToken", token). Downstream requests use Authorization: Bearer {{bearerToken}}.

Compare token strategies in Laravel Passport vs Sanctum before scripting OAuth flows. Sanctum personal access tokens are simpler for machine-to-machine smoke tests. Passport password grant or client credentials belong in collections only if your OAuth server still enables those grants in staging—many teams disable them and use a test-only client instead.

Separate environment files per target

Keep staging and production in distinct JSON files. Same collection, different baseUrl and credentials. Newman makes switching explicit:

npx newman run postman/collection.json -e postman/production.environment.json \
  --env-var "baseUrl=https://api.example.com" \
  --folder "Health and Readonly"

The --folder flag runs a subset—ideal for production jobs that must never hit destructive DELETE routes.

Pre-request scripts for dynamic headers

Idempotency keys, request signatures, and BS-date headers for Nepal-facing APIs sometimes need runtime values. Generate them in pre-request scripts:

const uuid = require('uuid');
pm.request.headers.add({
    key: 'Idempotency-Key',
    value: uuid.v4()
});

Cross-check idempotency behaviour against idempotency key implementation guides so tests match server semantics—not just header presence.

What should you assert in API test scripts for production APIs?

Weak assertions create false confidence. A test that only checks pm.response.code === 200 will miss broken pagination, missing VAT fields on NPR invoices, or silent schema drift.

Minimum assertion set per endpoint

  • HTTP status and meaningful error payload on failure paths.
  • Content-Type includes application/json where expected.
  • Required fields exist and types match (string, number, ISO date).
  • Response time under a budget for critical paths (pm.expect(pm.response.responseTime).to.be.below(800)).
  • Business invariants: cancelled bookings cannot return status active.

For legal-tech portals like Notary Nepal or payment-enabled client portals, assert that unauthorized roles receive 403—not 200 with empty data. That mistake ships more often than you'd expect after a policy refactor.

Contract and documentation alignment

When OpenAPI or Scribe docs exist, mirror documented fields in tests. If docs say meta.total on list endpoints, assert it. Drift between Scribe-generated API docs and live responses becomes visible immediately.

Consider JSON Schema validation via ajv in collection-level scripts for high-value payloads. One schema file checked into postman/schemas/ beats fifty copy-pasted field checks.

Negative and edge cases

Automate at least one malformed input test per write endpoint: missing required field, invalid enum, oversize string. Laravel validation should return 422 with structured errors. Assert the error key names your mobile app or frontend actually reads.

Read test automation strategy and the testing pyramid for placement: Newman suites are integration/smoke layer, not a replacement for unit tests or careful Laravel feature tests that seed databases in isolation.

How does Postman with Newman compare to PHPUnit and Insomnia for CI?

Teams often ask whether Newman duplicates PHPUnit. Usually it complements it. PHPUnit runs inside your app bootstrap with database transactions. Newman hits HTTP endpoints the way clients do—through routing, middleware, TLS termination, and reverse proxies.

CriteriaPostman + NewmanPHPUnit / Pest (Laravel)Insomnia + CLI
Runs in CI headlesslyYes, mature reportersYes, native to PHP stackLimited; Inso CLI exists but smaller ecosystem
Tests real HTTP stackYesPartial (HTTP kernel tests yes; full proxy path no)Yes
Non-developer friendlyStrong GUI for QA/productRequires PHP knowledgeGood GUI, weaker CI story
Database isolationUses shared staging DBRefreshDatabase, factoriesSame as Newman when hitting staging
Best fitSmoke, cross-service, webhook flowsBusiness logic, auth policies, edge casesManual exploration, ad-hoc calls

For a deeper tool comparison, see API testing with Postman, Newman, and Insomnia. My default on Laravel 12 projects: PHPUnit for domain logic, Newman for staging smoke after deploy, optional Playwright for true end-to-end UI paths.

When to Use Postman + NewmanNeed CI smoke tests?Hit live staging URL?YesNoUse NewmanPostman collection in CIUse PHPUnitIn-app feature testsBoth together: PHPUnit pre-merge, Newman post-deployCatches proxy, env, and integration regressions
Use API Testing Automation with Postman and Newman for staging smoke tests; keep PHPUnit for in-process Laravel logic and database isolation.

Engage testing and optimization services when you need help wiring Newman into an existing GitLab pipeline or designing a smoke suite for a legacy API without docs. For greenfield work under web development projects, bake collection export into Definition of Done from sprint one.

Key Takeaways

  • Export Postman collections and environments to Git; run the same suite locally with npx newman run before pushing.
  • Organise tests by business flow, chain IDs and tokens with collection variables, and assert behaviour—not just HTTP 200.
  • Inject secrets via CI masked variables; never commit live tokens or production admin credentials.
  • Run Newman against staging after deploy to exercise the full HTTP path, then gate production promotion on JUnit results.
  • Pair Newman smoke tests with PHPUnit feature tests and documented contracts so schema drift surfaces early.
  • Pin Newman and Node.js 26 LTS in package.json so CI and laptops execute identical command lines.

People Also Ask

Can Newman run Postman collections without the Postman desktop app?

Yes. Newman is a standalone CLI published on npm. Once you export collection and environment JSON files, no GUI is required on the server. Install with npm, run headlessly in Docker or GitLab runners, and parse exit codes for pass/fail. The Postman app is only needed for authoring and debugging tests interactively.

How do you fail a CI pipeline when Newman tests fail?

Newman exits with code 0 on success and non-zero when any assertion fails. CI systems treat non-zero exit codes as job failure automatically. Add JUnit reporters so GitLab or GitHub shows which request broke. Use --bail for fast failure or omit it to collect all failures in one run.

Is Postman Newman enough for full API test coverage?

No single tool covers everything. Newman excels at integration smoke tests against deployed environments. Unit-level validation, database transactions, and complex authorization matrices still belong in PHPUnit or Pest inside Laravel. Use both layers: PHPUnit on every commit, Newman on staging after deploy.

What is the difference between Postman Collection Runner and Newman?

Collection Runner is the GUI batch executor inside Postman—it is manual or semi-manual. Newman runs the same collection JSON from the terminal or CI with no human interaction, standardized reporters, and scriptable env-var injection. For API Testing Automation with Postman and Newman, treat Collection Runner as local debugging and Newman as the production automation path.

Ship APIs with confidence

API Testing Automation with Postman and Newman turns exploratory Postman work into a pipeline gate your team can trust. Start with one critical flow—auth plus one write/read pair—export the JSON, add a GitLab job, and expand folder by folder. Combine that smoke layer with Laravel feature tests and accurate docs so regressions surface before your users hit them. When you want help designing the suite or wiring CI for a Nepali payment or booking API, contact us or explore API development services. You can also browse the portfolio for Laravel platforms that rely on disciplined release testing—not hope.

Frequently Asked Questions

Postman designs HTTP requests and JavaScript test assertions; Newman runs the exported collection JSON headlessly in CI. You assert status codes and JSON fields once, then fail builds on every regression.

Yes. Newman is a standalone npm CLI. Export collection and environment JSON, install with npm, and run headlessly on CI runners or cron hosts—no Postman GUI required on the server.

Newman exits non-zero when any assertion fails. GitLab CI and GitHub Actions fail the job automatically. Add JUnit reporters so the pipeline tab shows exactly which request broke.

Organize one folder per user journey, not per HTTP verb. A booking flow might run authenticate, create booking, fetch booking, cancel booking. In the Tests tab, use pm.test and pm.expect to assert status, content type, required fields, and business states—not just 200 OK. Chain tokens and entity IDs with pm.collectionVariables.set so later requests read {{bookingId}} or {{bearerToken}}. Export Collection v2.1 JSON and a sanitized environment file into postman/ in Git, then add an npm test:api script so every developer runs Newman the same way before pushing.

Mirror CI locally with npm ci, then npx newman run postman/collection.json -e postman/staging.environment.json. Inject runtime secrets with --env-var, use --bail for fast failure, set --timeout-request 15000 to avoid hung callbacks, and export JUnit with --reporters cli,junit and --reporter-junit-export reports/newman.xml. In GitLab CI, use a node:26-bookworm image and run the same command against STAGING_BASE_URL after deploy—not before unit tests—so JUnit artifacts and exit code 1 block production promotion. Optional nightly read-only production smoke runs are fine if your SLA allows rate-limited monitoring credentials.

Auth is where CI suites break first: the GUI may hide a missing login step or an expired bearer token. Create a dedicated Auth folder that obtains a Laravel Sanctum personal access token or Passport token, then pm.environment.set bearerToken for downstream Authorization headers. Keep separate staging and production environment JSON files with different baseUrl values. For production Newman jobs, use --folder to run only Health and Readonly subsets so destructive DELETE routes never execute. Generate dynamic headers like Idempotency-Key in pre-request scripts when your API expects runtime values.

Tests that only check 200 OK miss schema drift, broken pagination, and silent authorization bugs. Minimum per endpoint: HTTP status and meaningful error JSON on failures, correct Content-Type, required field presence and types, response time budgets on critical paths, and business invariants like cancelled bookings not returning active. Assert unauthorized roles get 403, not 200 with empty data—a common regression after policy refactors on legal-tech and client portals. Mirror OpenAPI or Scribe documented fields. Add JSON Schema validation via ajv for high-value payloads. Automate at least one negative case per write endpoint expecting Laravel 422 with structured validation keys your frontend actually reads.

They complement rather than replace each other. PHPUnit and Pest bootstrap inside Laravel with database transactions and RefreshDatabase—ideal for business logic, auth policies, and edge cases. Newman hits real HTTP through routing, middleware, TLS, and reverse proxies the way clients and webhooks do. Insomnia offers a good GUI but weaker CI tooling compared to Newman's mature reporters. My default on Laravel 12 projects: PHPUnit on every commit, Newman staging smoke after deploy. Newman uses a shared staging database; PHPUnit stays isolated with factories.

Collection Runner is Postman's GUI batch executor—you trigger it manually inside the desktop app. Newman runs the same exported collection JSON from terminal or CI with no human interaction, standardized reporters, scriptable --env-var injection, and exit codes CI systems understand. If developers only click Send or use Collection Runner while CI runs Newman, drift appears fast: stale tokens, missing env vars, tests that pass only in GUI cache state. Standardize on npx newman run locally so laptops and pipelines execute identical command lines.

No single tool covers everything. Newman excels at integration and smoke tests against deployed staging or read-only production endpoints. Unit validation, database isolation, complex authorization matrices, and domain logic still belong in PHPUnit feature tests inside Laravel. Think testing pyramid: Newman is the integration smoke layer, not a replacement for in-process tests. Pair Newman with PHPUnit and documented contracts so schema drift surfaces early. Newman catches broken auth headers and cross-service webhook paths before production; PHPUnit seeds databases and asserts policy edge cases in isolation.

Never commit live tokens, API keys, or production admin credentials into exported environment JSON checked into Git. Use sanitized placeholders in postman/staging.environment.json and inject real values at runtime with Newman --env-var flags mapped to CI masked variables like API_TOKEN or STAGING_API_TOKEN, referenced as {{apiToken}} in requests. The same rule applies to nightly production smoke tests: use dedicated monitoring credentials with read-only scope, not superadmin tokens. Review CI logs so assertion output does not accidentally print sensitive response payloads during smoke runs.

On sister sites I maintain with Deployer 7 and GitLab CI, Newman API smoke tests run after deploy to staging—not before unit tests, but before promoting to production. The job hits a live staging URL with sandbox credentials so routing, PHP-FPM, TLS, and middleware behave like production. Exit code 1 plus JUnit artifacts gate the promotion step. Unit and feature tests still run earlier on every commit. Optional nightly Newman jobs against production read-only endpoints can catch drift if your SLA allows rate-limited monitoring credentials.

--env-var overrides baseUrl and apiToken at runtime without editing checked-in JSON. --bail stops on first failure for fast feedback; omit it when you want a full failure report. --timeout-request prevents hung third-party payment or webhook callbacks from blocking the pipeline. --reporters cli,junit with --reporter-junit-export reports/newman.xml lets GitLab show which assertion broke. --folder runs a subset like Health and Readonly for production jobs. Pin newman ^6.2.0 and Node.js 26 LTS in package.json so npm 12 resolves identical versions on laptops and runners.

Scope variables deliberately. Environment variables hold baseUrl, apiKey, and staging versus production flags—export separate JSON files per target. Collection variables store shared defaults with sanitized placeholders checked into Git. Local variables inside a single request script stay ephemeral. After login or create responses, pm.collectionVariables.set or pm.environment.set passes bookingId and bearerToken to the next request. Name folders after business workflows stakeholders understand—Checkout with Khalti callback beats POST /api/v1/payments—so another developer can maintain the suite six months later without reverse-engineering endpoint lists.

Auth and environment drift are the usual culprits. Postman GUI may cache tokens or skip the Auth folder while Newman runs headlessly from a cold start. Missing --env-var injections for secrets that exist only in your local Postman vault break bearer headers silently. Different baseUrl values between laptop and staging cause 404s that look like assertion failures. Tests asserting only pm.response.code === 200 pass even when response bodies are wrong. Developers who never run npx newman run before pushing miss these gaps. Run the exact CI command locally after npm ci to reproduce failures before the pipeline does.

Share this article

0 Comments

Leave a comment

Your email is not published. Comments appear once they have been read. Sign in to have your details filled in.

Quick Contact Options
Choose how you want to connect me: