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 with Postman Newman and Insomnia

By Kokil Thapa | Last reviewed: August 2026

Reliable backend systems require verification beyond manual browser checks or ad-hoc curl commands. Effective API testing with Postman Newman and Insomnia bridges the gap between local development exploration and production-grade continuous integration. While Insomnia excels at interactive debugging and design, Newman transforms Postman collections into headless test suites that validate your Laravel API best practices automatically within deployment pipelines.

How do you structure API testing with Postman Newman and Insomnia for PHP backends?

On real client projects, treating API clients as disposable scratchpads leads to fragile integrations and lost institutional knowledge. A sustainable workflow separates the design/debug phase from the automation/regression phase while keeping them synchronised. Insomnia serves as the primary workbench during active development because of its clean interface, native Git sync, and lightweight footprint. Once an endpoint stabilises, the collection migrates to Postman for Newman execution.

InsomniaDesign & DebugPostman CollectionCanonical SourceNewman CLIAutomated TestsCI / CD PipelineGate DeploymentAPI Testing with Postman Newman and Insomnia WorkflowExport from Insomnia → Validate in Postman → Automate with Newman → Block Bad Deploys
End-to-end workflow for API testing with Postman Newman and Insomnia across development and CI stages

This separation matters because Insomnia’s Git-native storage keeps request definitions close to application code, while Postman’s ecosystem provides the mature assertion library and reporter integrations Newman requires. For a legal-tech portal handling sensitive document uploads, this meant developers could iterate quickly in Insomnia during sprint work, then promote verified requests to the shared Postman collection that ran on every merge request. The key discipline is maintaining a single source of truth — never allow two divergent collections to coexist.

Environment variable strategy

Hardcoded URLs and tokens break the moment you move between local, staging, and production. Both tools support environment variables, but Newman demands explicit file-based environments for headless execution. Structure three files:

  • local.postman_environment.json — points to localhost:8000, uses dev database seeds, disables rate limiting
  • staging.postman_environment.json — targets staging server, uses test user credentials, includes realistic latency
  • production.postman_environment.json — read-only smoke tests only, never writes data, uses monitoring API keys

In Insomnia, mirror these as environment sub-environments. When exporting to Postman format, verify variable names match exactly — a mismatched {{base_url}} versus {{baseUrl}} causes silent failures that waste hours. I’ve encountered this during production deployments where the CI passed locally but failed on the runner because the exported collection used camelCase while Newman expected snake_case.

What are the key differences between Insomnia and Postman for Laravel API development?

Choosing between these tools isn’t about superiority — it’s about matching tool strengths to workflow phases. After years of building REST APIs for eCommerce platforms and service portals, the distinction has become clear: Insomnia optimises for developer velocity during creation, while Postman optimises for team coordination and automation at scale.

CriteriaInsomnia (2026)Postman + Newman
Primary strengthInteractive debugging, clean UI, Git-native storageTeam collaboration, assertions, CI/CD automation
Learning curveLow — minimal configuration neededModerate — collections, environments, test scripts
Version controlNative Git sync, YAML/JSON files in repoCloud-first; export required for repo storage
Test assertionsBasic response validationFull Chai.js assertion library, pre/post scripts
CLI automationLimited (insomnia-cli exists but less mature)Newman: battle-tested, extensive reporters
OpenAPI/design-firstStrong native spec editing and previewSupported but secondary to collection workflow
Cost (2026)Free core; paid for advanced sync/team featuresFree tier limited; teams require paid plan
Best for Nepal contextSolo devs, small teams, budget-sensitive projectsAgencies, multi-dev teams, compliance-heavy clients

For solo practitioners or small Nepali teams managing tight budgets, Insomnia often suffices for both development and basic regression testing. The free tier covers essential needs without cloud dependency — important when internet connectivity fluctuates. However, once a project involves multiple developers, external QA, or contractual SLAs requiring automated proof of API health, Postman’s ecosystem becomes necessary. On a recent multi-vendor marketplace project, we started with Insomnia for initial endpoint design, then migrated to Postman when the client required nightly automated test reports as part of the maintenance agreement.

When to use both

The pragmatic answer for most Laravel shops: use both. Keep Insomnia as your daily driver for exploratory testing and quick debugging. Maintain a curated Postman collection specifically for regression suites and CI gates. Export from Insomnia periodically to keep the Postman collection current, or use Insomnia’s export feature as part of your pre-commit hook. This avoids Postman’s UI overhead during active coding while retaining Newman’s automation guarantees.

How do you automate API testing with Postman Newman in GitLab CI?

Newman’s value emerges only when integrated into your deployment pipeline. Running tests manually defeats the purpose. For Laravel applications deployed via Deployer 7 and GitLab CI — a stack I use across multiple client sites including sister legal-tech portals — Newman fits naturally into the existing job structure.

Lint & UnitPHPStan + PestBuild AssetsVite + CommitDeploy StagingDeployer 7Newman TestsAPI RegressionProd DeployGatedGitLab CI Pipeline with Newman GateNewman runs AFTER staging deploy, BEFORE production promotionFailed tests block production deploy automatically
GitLab CI pipeline positioning Newman tests as a deployment gate after staging verification

Installing Newman in your CI runner

Newman requires Node.js. Since many PHP-focused CI runners lack Node, add it explicitly. For GitLab CI with a Docker executor:

<!-- .gitlab-ci.yml -->
api_tests:
  stage: test
  image: node:22-alpine
  script:
    - npm install -g newman newman-reporter-junitfull
    - newman run tests/postman/collection.json
      -e tests/postman/staging.postman_environment.json
      --reporters cli,junitfull
      --reporter-junitfull-export ./reports/newman-results.xml
  artifacts:
    when: always
    reports:
      junit: reports/newman-results.xml
  only:
    - merge_requests
    - main

The junitfull reporter integrates results directly into GitLab’s merge request UI, showing failed assertions inline. This visibility is critical — without it, Newman output gets buried in logs and developers ignore failures. On a legal services portal handling court date tracking, this integration reduced ignored test failures from frequent to nearly zero because broken tests appeared as visibly as failed PHP unit tests.

Handling authentication in CI

Most Laravel APIs use Sanctum or Passport. Hardcoding tokens in environment files committed to Git is a security failure. Instead, inject credentials at runtime:

# In GitLab CI variables (masked)
API_TEST_CLIENT_ID=3
API_TEST_CLIENT_SECRET=$CI_API_TEST_SECRET
API_TEST_USER=testuser@example.com

# In your Newman pre-request script or CI setup step
# Generate fresh token before test run
TOKEN=$(curl -s -X POST "$STAGING_URL/oauth/token" \
  -d "grant_type=password&username=$API_TEST_USER&password=$CI_TEST_PASS&client_id=$API_TEST_CLIENT_ID&client_secret=$API_TEST_CLIENT_SECRET" \
  | jq -r '.access_token')

# Pass to Newman as environment variable override
newman run collection.json -e staging.json --env-var "access_token=$TOKEN"

This pattern ensures tokens never persist in artifacts or logs. For Sanctum SPA authentication, use a dedicated test login endpoint that returns a session cookie, then configure Newman’s cookie jar accordingly. Never reuse production credentials — create test-specific users with scoped permissions matching what you’re validating.

How do you write effective test assertions for Laravel REST APIs?

A collection without assertions is just documentation. Assertions transform requests into verifiable contracts. Postman uses JavaScript (Chai.js assertion library) in the Tests tab. Focus on behaviour, not implementation details.

Essential assertion patterns

  1. Status code validation: Always assert expected HTTP status first. A 200 with wrong data is still a failure.
  2. Response schema: Verify JSON structure matches your API resource. Catch breaking changes early.
  3. Business logic: Confirm side effects occurred (e.g., order created, email queued).
  4. Performance baselines: Flag responses exceeding acceptable thresholds.
// Postman Test Script example for Laravel API endpoint
pm.test("Status code is 201", function () {
    pm.response.to.have.status(201);
});

pm.test("Response matches OrderResource schema", function () {
    const jsonData = pm.response.json();
    pm.expect(jsonData).to.have.property("data");
    pm.expect(jsonData.data).to.include.keys("id", "order_number", "total_npr", "status");
    pm.expect(jsonData.data.total_npr).to.be.a("number");
    pm.expect(jsonData.data.status).to.be.oneOf(["pending", "confirmed", "cancelled"]);
});

pm.test("Order total calculates correctly", function () {
    const jsonData = pm.response.json();
    const expectedTotal = pm.variables.get("expected_order_total");
    pm.expect(jsonData.data.total_npr).to.eql(expectedTotal);
});

pm.test("Response time under 500ms", function () {
    pm.expect(pm.response.responseTime).to.be.below(500);
});

For Nepal-based eCommerce handling NPR currency, always assert numeric types explicitly. JavaScript treats "1500" and 1500 differently in comparisons, and loose typing has caused real payment reconciliation bugs on grocery delivery platforms I’ve maintained. Also test edge cases specific to local context: Bikram Sambat date formatting, VAT-inclusive pricing calculations, and delivery zone validation for Kathmandu Valley versus outside-valley addresses.

What are you validating?Contract ShapeSchema validationRequired fieldspm.response.to.have...Business LogicCalculated valuesState transitionspm.expect().to.eql()Non-FunctionalResponse timeRate limit headerspm.response.responseTimeCombine all three layers for comprehensive coverageSchema catches breaking changes • Logic catches bugs • Performance catches regressions
Assertion decision framework for API testing with Postman Newman and Insomnia covering contract, logic, and performance layers

Testing error responses

Developers frequently test happy paths and neglect error handling. For Laravel Form Request validation, assert that invalid input returns 422 with correct error structure:

pm.test("Validation error returns proper structure", function () {
    pm.response.to.have.status(422);
    const jsonData = pm.response.json();
    pm.expect(jsonData).to.have.property("errors");
    pm.expect(jsonData.errors).to.have.property("email");
    pm.expect(jsonData.errors.email[0]).to.include("valid email address");
});

This catches regressions where exception handlers accidentally expose stack traces or return inconsistent formats — a common issue after upgrading Laravel versions or modifying global exception handling. On a notary service portal, this exact test prevented a production incident where a misconfigured middleware was returning 500 errors instead of validation messages for malformed document upload requests.

How do you maintain API test collections across Laravel upgrades?

Collections rot faster than application code. After upgrading multiple projects from Laravel 10 through 12, I’ve seen collections become unreliable within weeks if not actively maintained. Treat test collections as first-class code artifacts subject to the same review standards as PHP.

Version control and review process

Store Postman collections as JSON files in your repository under tests/postman/. Require merge requests for collection changes. During code review, verify that new endpoints have corresponding tests and that modified endpoints update assertions. For teams using Insomnia primarily, establish a weekly sync ritual: export updated requests to Postman format, run Newman locally against staging, commit passing collection updates. This prevents the drift that makes collections useless.

Managing breaking changes

When your Laravel API evolves (and it will), update collections before merging the backend change. Run Newman against the feature branch’s deployed preview environment. If tests fail, fix either the API or the test — never disable tests to pass CI. For versioned APIs following Laravel API versioning strategy, maintain separate collection folders per major version. Deprecate old version tests only after confirming zero production traffic via access logs.

Document intentional breaking changes in the collection itself using Postman’s description fields. Future developers debugging a failing test should immediately understand whether the failure indicates a bug or an expected contract change. This documentation pays dividends during onboarding and reduces the “why does this test exist?” questions that plague inherited projects.

Implementing Reliable API Testing with Postman Newman and Insomnia

Effective API testing with Postman Newman and Insomnia requires treating HTTP verification as an engineering discipline, not an afterthought. Start with Insomnia for rapid development feedback, curate Postman collections as living contracts, and enforce them through Newman in your CI pipeline. Assert behaviour over implementation, manage environments explicitly, and maintain collections with the same rigour as application code. For Laravel developers building systems that handle real transactions — whether eCommerce orders in NPR or legal document workflows — this investment prevents costly production incidents and builds client trust. If you need help establishing automated API testing for your PHP backend or integrating Newman into your existing deployment workflow, reach out to discuss your project.

Frequently Asked Questions

Newman is a CLI runner for executing existing Postman collections in automation pipelines, while Insomnia is primarily an interactive GUI client for manual debugging and design. Use Newman for CI/CD integration and regression suites; use Insomnia for exploratory testing and rapid endpoint validation during development.

Newman is free and open-source under Apache 2.0. Insomnia offers a free tier for individuals; team cloud sync starts around USD 12 per user monthly (approx NPR 1,600). For Nepal-based teams on tight budgets, I often recommend keeping local Postman exports with free Newman runners instead of paying recurring SaaS fees just for test execution.

Yes. Install newman and newman-reporter-htmlextra via npm in your pipeline job, then execute newman run collection.json -e environment.json --reporters cli,htmlextra. In my experience deploying Laravel APIs via GitLab CI, this provides immediate pass/fail feedback before deployment proceeds, catching breaking changes early without requiring a GUI or paid Postman cloud plan.

It depends on workflow preference. Insomnia has a cleaner interface, native GraphQL support, and less bloat for pure HTTP debugging. However, if you need automated testing via Newman or extensive team collaboration features already built into the ecosystem, Postman remains superior. On production Laravel projects, I frequently use both: Insomnia for quick checks during coding, Postman collections for formal QA and CI regression.

Never commit credentials to version control. Pass sensitive values as environment variables at runtime using newman run collection.json --env-var "api_key=$SECRET_KEY". In production CI pipelines for legal-tech portals handling sensitive documents, I inject these from GitLab CI masked variables or vault systems. This keeps tokens out of repository history while allowing automated tests to authenticate properly against staging environments.

Common causes include missing environment files, different Node.js versions, or hardcoded localhost URLs that don't resolve in containerized runners. Always parameterize base URLs using environment variables rather than hardcoding endpoints. Verify your local Node version matches CI (Node 22 LTS recommended for 2026). I've debugged this repeatedly on Laravel API projects where developers forgot to export their local .env equivalents before running Newman manually.

Yes. Insomnia supports importing Postman v2.1 JSON exports natively via File > Import > Postman Collection. However, complex pre-request scripts, certain auth helpers, or proprietary Postman features may not translate perfectly. Test imported collections thoroughly before relying on them. When migrating teams between tools, I validate critical workflows manually first rather than assuming lossless conversion.

Install newman-reporter-htmlextra via npm, then add --reporters htmlextra --reporter-htmlextra-export ./reports/report.html to your command. The output includes request/response details, assertions, and timing metrics in a browsable format. On client projects, I archive these as CI artifacts so stakeholders can review API health without accessing raw logs or needing Postman installed locally.

Organize by resource domain (users, orders, payments) with nested folders mirroring your route structure. Separate authentication setup into dedicated pre-request scripts or collection-level authorization. Maintain distinct environment files for local, staging, and production. On eCommerce platforms like Nepal Gift Card, this modular approach lets us run targeted subset tests during feature development while preserving full regression coverage for releases.

Yes. Use the --iteration-data flag pointing to a CSV or JSON file containing test datasets. Each row triggers a separate iteration with variables substituted dynamically. This is essential for validating edge cases across multiple inputs without duplicating requests. I've used this pattern extensively on booking systems to verify pricing logic across dozens of date and guest combinations efficiently within a single collection run.

Configure OAuth2 at the collection level with auto-refresh enabled, or write a pre-request script that checks token expiry and fetches new credentials before dependent requests execute. Store refreshed tokens in environment variables using pm.environment.set(). For Laravel Sanctum or Passport APIs, I typically create a dedicated login request that runs first and propagates the bearer token to subsequent calls automatically.

Insomnia introduced Inso CLI for automation, supporting collection runs and reporting similar to Newman. However, its ecosystem and reporter options remain less mature. If your team already maintains Postman collections, switching to Inso adds migration overhead with limited benefit. I evaluate Inso only when starting fresh projects where no legacy Postman assets exist and the simpler UX outweighs Newman's broader plugin support.

Check assertion syntax carefully; Postman uses Chai-style expect() or pm.test() blocks inside the Tests tab. Ensure response parsing handles content-type correctly (JSON vs plain text). Verify variable interpolation isn't producing unexpected strings. A frequent issue I encounter involves whitespace mismatches or type coercion failures when comparing numeric IDs returned as strings. Add console.log(pm.response.text()) temporarily to inspect actual payloads during debugging.

Run Newman as a post-deploy verification step in your Deployer 7 or GitLab CI pipeline after PHP-FPM reloads. Target the freshly deployed staging URL with appropriate environment config. Fail the pipeline if any critical endpoint returns errors. On sister sites sharing infrastructure like notarykathmandu.com, this catches misconfigured routes or database migration issues immediately after symlink swaps, preventing broken production releases from going unnoticed until users report them.

Avoid hardcoding URLs, skipping negative test cases, ignoring response schema validation, and treating tests as documentation-only artifacts. Version-control your collections alongside application code. Parameterize everything environment-specific. Start small with happy-path smoke tests before building exhaustive suites. In practice, teams that treat API tests as living contracts tied to deployment pipelines gain far more value than those maintaining stale collections nobody actually executes regularly.

Share this article

Quick Contact Options
Choose how you want to connect me: