
September 10, 2026
12 min read
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.
newman run to fail builds on regression and publish JUnit reports.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.
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.
Export both files to version control:
- Collection → Export → Collection v2.1 JSON →
postman/collection.json - Environment → Export →
postman/staging.environment.json - 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.
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.
| Criteria | Postman + Newman | PHPUnit / Pest (Laravel) | Insomnia + CLI |
|---|---|---|---|
| Runs in CI headlessly | Yes, mature reporters | Yes, native to PHP stack | Limited; Inso CLI exists but smaller ecosystem |
| Tests real HTTP stack | Yes | Partial (HTTP kernel tests yes; full proxy path no) | Yes |
| Non-developer friendly | Strong GUI for QA/product | Requires PHP knowledge | Good GUI, weaker CI story |
| Database isolation | Uses shared staging DB | RefreshDatabase, factories | Same as Newman when hitting staging |
| Best fit | Smoke, cross-service, webhook flows | Business logic, auth policies, edge cases | Manual 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.
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 runbefore 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
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.

