API Testing: Postman/Newman
1) Why Postman/Newman
Postman is a handy IDE for scripts and query collections. Newman is a CLI engine that runs the same collections without GUI in CI/CD. Together they give:- repeatable regressions and rapid smokes;
- parameterization of environments/secrets;
- quality metrics and machine-readable reports.
2) Base model
Collection - a tree of queries and folders with common scripts.
Environments - set '{{vars}}' for dev/stage/prod (URL, keys).
Pre-request script - preparation: signatures, tokens, data correlation.
Tests - assertions and preservation of variables/artifacts.
Data-files - CSV/JSON for data-driven run.
Mock/Monitor - flocks and periodic checks.
<API v1>
├─ _bootstrap (auth, health, seeds)
├─ Public
├─ Authenticated
│ ├─ Accounts
│ ├─ Payments
│ └─ Reports
└─ _teardown (cleanup)
3) Variables and secrets
Refer to variables as explicit prefix: 'baseUrl', 'tenant', 'clientId'.
Keep secrets (passwords, client_secret, HMAC keys) in CI environment variables, do not commit to the repository.
Use the scope: local → collection → environment → globals.
json
{
"name": "stage-eu",
"values": [
{"key":"baseUrl","value":"https://api. stage. example. com","type":"text","enabled":true},
{"key":"tenant","value":"eu-1","type":"text","enabled":true}
]
}
4) Authentication: templates
4. 1 OAuth2/OIDC (Client Credentials)
Pre-request:js if (!pm.environment. get("access_token") Date. now() > pm. environment. get("token_exp")) {
pm. sendRequest({
url: pm. environment. get("authUrl"),
method: 'POST',
header: {'Content-Type':'application/x-www-form-urlencoded'},
body: { mode:'urlencoded', urlencoded:[
{key:'grant_type',value:'client_credentials'},
{key:'client_id',value:pm. environment. get('clientId')},
{key:'client_secret',value:pm. environment. get('clientSecret')},
{key:'scope',value:'payments:read payments:write'}
]}
}, (err, res) => {
pm. environment. set("access_token", res. json(). access_token);
pm. environment. set("token_exp", Date. now()+ (res. json(). expires_in-30)1000);
});
}
In the request: 'Authorization: Bearer {{access _ token}}'.
4. 2 HMAC (Webhooks/Partners)
Pre-request:js const body = pm. request. body? pm. request. body. raw '': '';
const ts = Math. floor(Date. now()/1000);
const msg = `${ts}.${body}`;
const sig = CryptoJS. HmacSHA256(msg, pm. environment. get('hmacSecret')). toString();
pm. variables. set('ts', ts);
pm. variables. set('sig', sig);
Titles: 'X-Timestamp: {{ts}}', 'X-Signature: {{sig}}'.
5) Tests: assertions and correlation
Use 'pm. expect(...)` и `pm. test("...", fn)`.
Store IDs for subsequent steps via 'pm. collectionVariables. set`.
js pm. test("HTTP 200", () => pm. response. to. have. status(200));
pm. test ("Scheme is valid," () => {
const schema = pm. collectionVariables. get("schema_wallet");
pm. expect(tv4. validate(pm. response. json(), JSON. parse(schema))). to. be. true;
});
pm. test ("Contains id," () => {
const id = pm. response. json(). id;
pm. expect(id). to. be. a('string');
pm. collectionVariables. set("wallet_id", id);
});
6) Schema validation (OpenAPI/JSON Schema)
Store the JSON Schema in collection variables or in a separate file.
For OpenAPI: use ready-made libs in pre-request/test (ajv, tv4) - via 'pm. sendRequest 'to raw file or JSON inline.
js pm. collectionVariables. set("schema_wallet", JSON. stringify({
"type":"object",
"required":["id","currency","balance"],
"properties":{
"id":{"type":"string"},
"currency":{"type":"string","pattern":"^[A-Z]{3}$"},
"balance":{"type":"number","minimum":0}
}
}));
7) Data-driven scripts
CSV:
email, password, currency u1@example. com, P@ss1, EUR u2@example. com, P@ss2, USD
Query uses' {{email}} ',' {{currency}} '.
Launch:
newman run collection. json -e stage-eu. json -d users. csv
JSON (array of objects) - convenient for complex cases/structures.
8) Negative cases and resilience
Cover:- 401/403 (no token/invalid scope/role).
- 400/422 (validation of the scheme, mandatory fields, limits).
- 404 (BOLA/alien resource).
- 409 (conflicts, idempotent keys).
- 429 (limits) - check 'Retry-After'.
- 5xx - correct degradation and retro client.
js pm. test ("There is Retry-After at 429," () => {
if (pm. response. code === 429) pm. expect(pm. response. headers. has('Retry-After')). to. be. true;
});
9) Idempotence, retrae, pagination
Pass'Idempotency-Key 'and make sure that the repetition gives the same' id/status'.
Test pagination: 'limit/offset '/' cursor', the detection of duplicates and gaps.
Simulating retrays in a Test script: consecutive calls with the same key.
js pm. test ("Idempotent repetition," () => {
pm. sendRequest(pm. request, (err, res2) => {
pm. expect(res2. code). to. eql(pm. response. code);
pm. expect(res2. json(). id). to. eql(pm. response. json(). id);
});
});
10) Newman в CI/CD
10. 1 Launch
newman run collection. json \
-e stage-eu. json \
-d data. csv \
--timeout-request 30000 \
--reporters cli,htmlextra,junit \
--reporter-htmlextra-export./reports/report. html \
--reporter-junit-export./reports/junit. xml
10. 2 GitHub Actions (snippet)
yaml
- uses: actions/setup-node@v4 with: { node-version: '20' }
- run: npm i -g newman newman-reporter-htmlextra
- run: newman run collection. json -e stage-eu. json --reporters cli,junit --reporter-junit-export reports/junit. xml
- uses: actions/upload-artifact@v4 with: { name: newman-reports, path: reports }
10. 3 Jenkins/GitLab CI
Export JUnit ('--reporter-junit-export') for native rendering.
In the pipeline, separate the jabs: smoke (fast), regression (full), security (negative/boundaries).
10. 4 Docker
docker run --rm -v $PWD:/etc/newman postman/newman \
run collection. json -e stage-eu. json
11) Moki and monitoring
Mock servers Postman - fast stacks for front and contracts.
Monitors - periodic run of clouds from the cloud (latency, 5xx, SSL).
In the repository, keep sample response files for deterministic mocs.
12) Test data and cleaning
Create/delete entities (_bootstrap/_teardown).
Label test objects with the prefix 'e2e _' and TTL.
js pm. collectionVariables. set("uniq", Date. now()+"_"+Math. floor(Math. random()1e6));
13) Performance "on the knee"
Postman is not a loading tool, but:- measure'pm. response. responseTime`;
- run 5-10 iterations and fix p95/thresholds;
- heavy performance runs - in JMeter/k6/Gatling (outside of this article).
14) Localization and multi-tenancy
Variables' tenant ',' region ',' lang '; switch in environments.
Tests should check that data does not "flow" between tenants (BOLA-read, cross-tenant prohibitions).
Separate collections/folders for regional features (limits, currencies).
15) Reporting and artifacts
Store CI artifacts: HTML reports, 'junit. xml ', response bodies.
Connect Slack/Teams notifications for shock drops.
16) Quality and coverage
Coating matrix:- CRUD per-resource (200/201/204 + negatives).
- Authorization: roles/scopes/multi-tenant.
- Pagination/filters/sorting.
- Idempotence and retreats.
- Limits: 413/414/431/429.
- Formats and schemas (JSON Schema/OpenAPI).
- Integrations (webhooks with HMAC/mTLS) - anti-replay.
17) Antipatterns
One "happy way" without negative tests.
Long-lived tokens in the collection/repository.
Mixing test data with production data.
Latent test order dependency without explicit correlation.
Giant data-files without sampling.
No JUnit/HTML reports → no visibility in CI.
18) Prod Readiness Checklist
- Collections are broken down by domain, there is' _ bootstrap/_ teardown '.
- Environments for dev/stage/prod; secrets from CI-secret-storage.
- Pre-request для auth (OAuth2/HMAC); tokens are cached and rotated.
- Tests: positive + negative, schemes (JSON Schema), pagination, 429/Retry-After.
- Idempotency: Check'Idempotency-Key ', double call equivalent.
- Data-driven CSV/JSON, random suffixes for uniqueness.
- Newman in CI: JUnit/HTML reports, artifacts as build outputs.
- Mocks/monitors for key routes; SLA on figs.
- Documentation of variables, tags, and launch order.
19) TL; DR
Store test logic in Postman collections, parameters in environments, and run in CI via Newman with JUnit/HTML reports. Cover negatives, schemas, idempotency, pagination and limits. Correlate steps with variables, use data-driven inputs and washes/monitors. Secrets - only from CI, reports - build artifacts.