xtest

API Testing

API Testing with Postman and Newman

This course teaches you how to test REST APIs using Postman, the widely used API client, and how to automate those tests at the command line and in continuous integration pipelines with Newman, Postman's command-line companion. You will learn to build collections of requests, organize them with folders and variables, write assertions with Postman's test scripts, chain requests together using data from previous responses, manage environments for different stages of development, and run entire test suites automatically every time code changes. By the end of the course you will be able to design a maintainable API test suite from scratch, convert manual exploratory testing into repeatable automated checks, and wire that suite into a build pipeline so that a broken API is caught before it reaches users. The course is written for testers and developers who already understand what an API is and want practical, hands-on skills with real tools.

Beginner · By the Xtest team · About 24 minutes to read

Introduction

Modern applications are built from many services that talk to each other over HTTP, and most of the logic a user never sees lives behind an API rather than in a page they click through. Testing at that layer, before a user interface even exists, catches problems earlier and more cheaply than testing only through a browser, and it is a skill every QA engineer is expected to have alongside UI testing.

Postman is a graphical tool for building, sending and organizing HTTP requests, and it has grown into one of the standard ways testers and developers explore and verify an API by hand. Newman is the command-line tool that runs a Postman collection outside the Postman application, which is what turns a collection you built by hand into something a build server can run on every commit.

This course takes you from installing Postman and sending your first request, through writing assertions that turn a request into a real test, to exporting a collection and running it with Newman inside a continuous integration pipeline. Along the way you will learn to manage variables and environments so the same collection can run against a local server, a staging server and a production server without being rewritten, how to chain requests so that data created in one call is used to verify another, and how to read and act on the reports Newman produces. Each section builds on the last with working examples you can run yourself, exercises that ask you to extend those examples, and a quiz to check your understanding. No prior experience with Postman is assumed, though you should already be comfortable with the basic idea of an HTTP request and response.

Getting Started with Postman: Installation, Collections, and Requests

Why Postman

Postman is a desktop and web application for building and sending HTTP requests by hand. Instead of writing a script every time you want to check an endpoint, you fill in a URL, pick a method, add headers or a body, and press Send, then read the response in a readable panel. That makes it a fast way to explore an API you did not build yourself, and a practical way to start automating tests once you understand how the API behaves.

Collections, Requests and Folders

A collection is a named group of saved requests. Inside a collection you can create folders to group related requests, for example one folder for everything under /users and another for /orders. Each saved request remembers its method, URL, headers, body and any tests you attach to it, so you do not have to retype it every time.

A typical first collection for a small API might have:

  • A folder named Users containing GET /users, POST /users, GET /users/{id}, PUT /users/{id} and DELETE /users/{id}
  • A folder named Auth containing POST /login and POST /logout

Sending Your First Request

To send a request you choose the HTTP method from the dropdown (GET, POST, PUT, PATCH, DELETE and others), type the URL, and for methods that send a body you choose a body type, most often raw with the format set to JSON. When you press Send, Postman shows you the status code, the response time, the response size and the full response body, along with the response headers in a separate tab.

Variables

Typing the same base URL into every request is slow and error-prone, so Postman lets you define a variable, for example {{baseUrl}}, and use it inside any request's URL, headers or body. Variables can live at the collection level, shared by every request in that collection, or at the environment level, described in a later section, which is what lets the same collection point at different servers.

Importing and Exporting

A collection can be exported as a single JSON file, which is what you share with a teammate or feed into Newman later, and it can be imported back the same way. Many APIs also publish an OpenAPI or Postman collection file directly, which you can import instead of building every request by hand.

This section gives you the foundation every later section builds on: a working collection of real requests against a real API, organized clearly enough that adding tests to it in the next section will be straightforward.

Installing Postman and Creating Your First Collection

Postman is available as a desktop application for Windows, macOS and Linux, and also as a web application that runs in the browser once you sign in with a free account. For this course, install the desktop application, since it is what most teams use day to day and it is what Newman's reports will later match.

Once installed, open Postman and create a new collection by clicking the plus icon next to Collections in the left sidebar, or choosing New then Collection from the top menu. Give it a clear name, for example JSONPlaceholder API Tests, since the examples in this course use the free public testing API at https://jsonplaceholder.typicode.com, which simulates a small blog with posts, comments and users and accepts requests without any authentication.

Inside your new collection, add a request by clicking the three dots next to the collection name and choosing Add Request, or by using the plus tab at the top of the request builder. Name the request something descriptive like Get all posts, set the method to GET, and set the URL to https://jsonplaceholder.typicode.com/posts. Press Send. You should see a 200 status code and a JSON array of post objects in the response body.

Repeat this to build out a handful of requests: GET /posts/1 to fetch a single post, POST /posts with a JSON body to create one, and GET /users to list users. Save each one into the collection as you go, using Ctrl+S or Cmd+S, since an unsaved request disappears when you close Postman. By the end of this exercise you should have a named collection containing at least four saved, working requests.

Working with Headers, Request Bodies and Response Inspection

Most real APIs expect certain headers on a request, most commonly Content-Type: application/json on any request that sends a JSON body, and often an Authorization header carrying a token or API key. In Postman, headers are set in the Headers tab of the request builder, as a list of key and value pairs; Postman adds some headers automatically, such as Content-Type, when you choose a body type, so you do not always have to add them by hand.

For a POST or PUT request, open the Body tab, choose raw, and set the format dropdown to JSON. Then type the JSON object you want to send, for example:

{
  "title": "My new post",
  "body": "This is the content of the post",
  "userId": 1
}

When you press Send, Postman serializes this exactly as typed and sends it as the request body.

Once a response comes back, the response panel shows several tabs. The Body tab shows the raw response, which Postman pretty-prints and syntax-highlights when the content type is JSON. The Headers tab lists every header the server sent back, which matters when you need to check things like Content-Type, caching headers or a rate-limit header. The status line above the body shows the HTTP status code, for example 200, 201 or 404, along with the response time in milliseconds and the response size, both useful when you later add performance-related assertions.

Getting comfortable reading this panel by eye, before writing a single line of a test script, is what makes the assertions you write in the next section meaningful rather than guesswork.

curl -X GET https://jsonplaceholder.typicode.com/posts/1 \
  -H "Accept: application/json"

The same request you build in Postman's UI, expressed as a curl command. Running this in a terminal returns the same JSON body you see in Postman's response panel, which is a useful way to confirm Postman is not doing anything hidden.

curl -X POST https://jsonplaceholder.typicode.com/posts \
  -H "Content-Type: application/json" \
  -d '{"title": "My new post", "body": "This is the content", "userId": 1}'

A POST request with a JSON body and an explicit Content-Type header, matching the request you create in the Body tab exercise above. Comparing this to the Postman request helps you see exactly what fields in the UI correspond to what parts of the raw HTTP request.

Tips

  • Save requests into clearly named folders as you create them rather than at the end; a collection with ten unsorted requests is much harder to navigate than one organized from the start.
  • Use a public, free testing API such as JSONPlaceholder while you are learning, so you are never blocked by authentication or rate limits while practicing the basics.
  • Turn on the response preview's raw view occasionally, not just the pretty JSON view, so you get used to reading an API's actual bytes, including any trailing content or unexpected formatting.

Common pitfalls

  • Forgetting to save a request after editing it: Postman does not always warn you before you navigate away, so changes can be lost. Get into the habit of pressing Ctrl+S or Cmd+S after any edit.
  • Sending a JSON body without setting Content-Type to application/json: some servers will still accept it, but others will reject or misinterpret the body, producing confusing errors that have nothing to do with the JSON itself. Always check the Headers tab matches the body type you chose.

Writing Tests and Assertions in Postman

Postman's Tests tab lets you attach JavaScript to any request so that, once a response comes back, you can automatically check whether the API behaved as expected. These scripts run inside the Postman Sandbox, a lightweight JavaScript environment that exposes the pm object, giving you access to the response, request, environment variables, and a pm.test() function for defining named assertions.

At its core, pm.test('description', function () { ... }) wraps one or more assertions, and Postman reports each test block as pass or fail in the Test Results panel after the request runs. Inside that callback, pm.expect() (built on Chai's BDD-style syntax) lets you assert on status codes, headers, response time, and the parsed JSON body.

Beyond single-request checks, tests become powerful when chained: you can pull a value out of one response (an id, a token, a timestamp) and store it with pm.environment.set() or pm.collectionVariables.set(), then reference that variable in a later request's URL, headers, or body. This lets you build realistic multi-step flows, such as creating a resource, then fetching it, then deleting it, all within one collection run.

When a test script doesn't behave as expected, the Postman Console (View > Show Postman Console) is indispensable. It logs every request and response in full, plus any console.log() statements you add to your script, making it far easier to see exactly what data you're asserting against. For teams that want consistency, Postman also supports folder-level and collection-level pre-request and test scripts, which run before or after every request inside that scope, so you can centralize common checks (like 'every response must return within 500ms') instead of repeating them request by request.

Core Assertions: Status, Body, Headers, and Timing

The most common assertion checks the HTTP status code: pm.response.to.have.status(200) confirms the server responded as expected, and you can also check for a range or a list of acceptable codes. For the response body, pm.response.json() parses the payload so you can assert on individual fields, for example pm.expect(jsonData.name).to.eql('Alice'). When an API's shape matters more than specific values, schema validation with pm.response.to.have.jsonSchema(schema) checks that the response matches a predefined JSON Schema, catching structural regressions like a missing field or wrong type even when exact values vary.

Headers deserve their own checks too: pm.response.to.have.header('Content-Type') confirms a header exists, and you can go further by asserting on its value, such as making sure Content-Type includes application/json. Timing matters for performance-sensitive endpoints; pm.expect(pm.response.responseTime).to.be.below(500) fails the test if the response takes longer than half a second, which is useful for catching slow endpoints before they reach production.

A well-rounded test script typically combines several of these checks in one request: status code, a couple of key body fields, a required header, and a timing budget. Writing them as separate pm.test() blocks (rather than one giant block) means a single failure doesn't hide whether the other checks passed, giving you a clearer picture in the Test Results panel of exactly what broke.

Chaining Requests and Reusable Scripts

Real-world API testing rarely stops at one request. A typical flow might create a user, capture the returned id, then use that id in a follow-up request to fetch or update that user. The pattern is: in the first request's Tests tab, extract the value from the JSON response and save it with pm.environment.set('userId', jsonData.id). In the second request, reference it in the URL as {{userId}}, and Postman substitutes the stored value automatically when the collection runs.

This chaining technique is what makes Postman collections useful for testing entire workflows rather than isolated endpoints, and it's the same mechanism Newman relies on when running a collection from the command line, since environment and collection variables persist across requests within a single run.

To avoid duplicating the same assertions across dozens of requests, Postman supports pre-request and test scripts at the folder and collection level. A script attached to a folder runs automatically before or after every request nested inside it, so a check like 'the response must always be valid JSON' or 'the Authorization header must always be present' can live in one place instead of being copy-pasted into every request. This also makes maintenance easier: if a shared assumption changes (say, a new required header), you update the folder-level script once rather than hunting through every request in the collection.

// Tests tab for a GET /users/{{userId}} request
pm.test('Status code is 200', function () {
    pm.response.to.have.status(200);
});

const jsonData = pm.response.json();

pm.test('Response has correct user id', function () {
    pm.expect(jsonData.id).to.eql(pm.environment.get('userId'));
});

pm.test('Response time is acceptable', function () {
    pm.expect(pm.response.responseTime).to.be.below(500);
});

pm.test('Content-Type header is present', function () {
    pm.response.to.have.header('Content-Type');
});

console.log('Fetched user:', jsonData);

A complete test script checking status, a body value against a stored variable, response time, and a header, with a console.log for debugging in the Postman Console.

// Tests tab for a POST /users request, chaining into later requests
const jsonData = pm.response.json();

pm.test('User was created with status 201', function () {
    pm.response.to.have.status(201);
});

// Save the new user's id for use in subsequent requests
pm.environment.set('userId', jsonData.id);

Extracts an id from a creation response and stores it as an environment variable so that a following request in the collection can reference it as {{userId}}.

Tips

  • Write each assertion as its own pm.test() block so one failure does not mask the results of the others in the Test Results panel.
  • Use pm.response.to.have.jsonSchema() when you care about the overall shape of a response, not just a few field values, so structural regressions get caught too.
  • Use console.log() liberally inside test scripts and check the Postman Console to see exactly what data a failing assertion was working with.

Common pitfalls

  • Forgetting that pm.response.json() throws if the body is not valid JSON; wrap body assertions in a check for content type first, or the whole test script can abort silently.
  • Setting a variable with pm.environment.set() but then running the collection with a different environment selected, so the variable the next request reads is empty or stale; always confirm which environment is active before a chained run.

Automating API Tests with Newman and CI/CD Integration

Postman collections are great for manual exploration, but the real value of API testing comes from running those same collections automatically, on every commit, without a human clicking Send. Newman is the command-line companion to Postman: it takes an exported collection (and optionally an environment file) and runs every request and test script exactly as Postman would, then reports pass/fail results in a format a build server can understand.

This section walks through the full path from a collection sitting in your Postman workspace to a pipeline that blocks a merge when an endpoint breaks. You will export your collection and environment as JSON, install Newman locally, run it from the terminal, and read its console output line by line to understand which assertion failed and why. From there you will generate an HTML report for sharing with teammates who do not live in the terminal, feed Newman a CSV or JSON data file so the same collection runs once per row of test data, and finally wire the whole thing into GitHub Actions, GitLab CI or Jenkins so it runs unattended and fails the build the moment a test fails.

By the end of this section you should be able to take any collection you have built in earlier sections and turn it into a repeatable, automated regression suite that protects your API as the codebase changes underneath it.

Installing Newman and Running Your First Collection

Newman is distributed as an npm package, so it needs Node.js installed first. Install it globally with npm install -g newman so the newman command is available from any folder, or install it as a dev dependency in a project with npm install --save-dev newman if you want the version pinned in package.json for reproducible builds.

Before running Newman you need two files out of Postman: the collection itself, exported from the collection's context menu as a Collection v2.1 JSON file, and, if your requests use variables like {{baseUrl}} or {{apiKey}}, the environment exported the same way. Keep these files in your project repository alongside your source code so they version alongside the API they test.

A basic run looks like newman run collection.json -e environment.json. Newman executes every request in order, runs the test scripts attached to each one, and prints a summary table showing how many assertions passed and failed per request, followed by a full failure list if anything broke. Reading this output is a skill in itself: a failing assertion names the test description you wrote in the Postman test script, so writing clear, specific descriptions when you build your tests pays off later when a build fails at 2am and someone has to work out what broke from the log alone.

Newman also accepts an iteration count (-n 5) to repeat the whole collection, and a --bail flag to stop at the first failure instead of running every request regardless, which is useful when a setup request fails and every later request would fail anyway as a result.

Data-Driven Runs and HTML Reports

Real APIs need to be tested with more than one input: different user IDs, boundary values, invalid payloads. Rather than writing a separate request for each case, Newman can iterate a single collection over rows of a CSV or JSON data file with newman run collection.json -d data.csv. Each column header in the CSV becomes a variable available inside your test scripts as pm.iterationData.get('columnName'), so one request definition can validate dozens of input combinations in a single run, which is exactly the pattern to use when checking input validation or pagination boundaries.

Console output is fine for a terminal but unreadable for a teammate who was not watching the run happen, so Newman supports reporters. The built-in HTML reporter is enabled with --reporters cli,html, and by default writes to a newman folder in your working directory; you can control the output path with --reporter-html-export path/to/report.html. The HTML report lists every request, its response time, and every assertion with a clear pass or fail marker, which makes it the artifact worth attaching to a build or sharing after a nightly run.

A common pattern is to keep a small, fast smoke collection with a handful of critical requests for every commit, and a larger data-driven regression collection with wide input coverage that runs on a schedule or before a release, since full data-driven runs can take noticeably longer and are not always worth blocking every push on.

# Install Newman as a project dependency
npm install --save-dev newman newman-reporter-html

# Run a collection with an environment and a data file,
# producing both console output and an HTML report
npx newman run collection.json \
  -e environment.json \
  -d testdata.csv \
  --reporters cli,html \
  --reporter-html-export newman/report.html \
  --bail

Installs Newman locally in a project, then runs a collection against an environment file, iterating over a CSV data file, producing both a terminal summary and an HTML report, stopping on the first failure.

name: API Tests

on: [push, pull_request]

jobs:
  newman:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: '20'
      - name: Install Newman
        run: npm install -g newman
      - name: Run API test collection
        run: newman run collection.json -e environment.json --reporters cli,junit --reporter-junit-export results.xml
      - name: Upload test results
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: newman-results
          path: results.xml

A GitHub Actions workflow that checks out the repository, installs Node and Newman, runs the API collection on every push and pull request, exports a JUnit-format report, and uploads it as a build artifact even when the step fails.

Tips

  • Pin Newman's version in package.json rather than installing it globally in CI, so a Newman update never silently changes your pipeline's behavior.
  • Export environments without secrets baked in; pass sensitive values like API keys as CI pipeline secrets and inject them with Newman's `--env-var` flag instead of committing them to the exported JSON.
  • Write descriptive test names inside your Postman test scripts (the string passed to pm.test), since that description is the only context you get in Newman's console and HTML output when a test fails.

Common pitfalls

  • Forgetting to re-export the collection or environment after editing them in Postman, so the CI pipeline keeps running an outdated version; export as part of your release checklist or use Postman's API to pull the latest version automatically.
  • Letting a data-driven collection with many iterations run on every single commit, which slows down feedback for developers; reserve large data-driven runs for a scheduled job and keep the per-commit suite small and fast.

Exercises

Exercise 1: Build a Posts Collection

In this exercise you will build a complete Postman collection against the free JSONPlaceholder API, covering the main CRUD operations for the posts resource. The goal is not yet to write test assertions, which is covered in the next section, but to get comfortable creating, organizing and saving requests so that the collection is a solid foundation to add tests to afterward. Pay attention to naming: a request named clearly, such as 'Create a new post' rather than 'Request 1', makes the collection far easier for a teammate, or your future self, to understand without opening every request. You will also practice using a collection-level variable for the base URL, which is the first step toward making a collection reusable across environments. Take your time inspecting each response before moving to the next request, since understanding what a normal, successful response looks like is what will let you recognize an abnormal one later.

  1. Create a new collection named 'JSONPlaceholder Posts'.
  2. Add a collection variable named baseUrl with the value https://jsonplaceholder.typicode.com.
  3. Create a GET request to {{baseUrl}}/posts and confirm it returns a 200 status with a JSON array.
  4. Create a GET request to {{baseUrl}}/posts/1 and confirm it returns a single post object.
  5. Create a POST request to {{baseUrl}}/posts with a JSON body containing title, body and userId fields, and confirm it returns a 201 status.
  6. Create a PUT request to {{baseUrl}}/posts/1 that updates the title field, and confirm the response reflects your change.
  7. Create a DELETE request to {{baseUrl}}/posts/1 and confirm it returns a 200 status.
  8. Organize all five requests into a folder named Posts inside the collection, and save everything.

Expected outcome: A saved Postman collection named 'JSONPlaceholder Posts' containing a Posts folder with five working requests covering GET (list), GET (single), POST, PUT and DELETE, all using the {{baseUrl}} variable instead of a hardcoded URL, each verified by hand to return the expected status code and body shape.

Exercise 2: Add Assertions to the Collection

Building on the collection from Exercise 1, this exercise asks you to add real test scripts to each request so that pressing Send no longer requires you to read the response by eye to know whether it passed. You will use the Tests tab in Postman and the pm.test and pm.expect functions to check status codes and key fields in the response body. This is the step that turns a collection of manual requests into an automated test suite, which is also what makes the collection meaningful to run later with Newman. Focus on writing assertions that would actually catch a real bug, for example checking that a created post's title in the response matches the title you sent, rather than only checking the status code.

  1. Open the GET /posts request and add a test asserting the status code is 200.
  2. Add a second test on the same request asserting the response body is an array.
  3. Open the GET /posts/1 request and add a test asserting the returned post's id field equals 1.
  4. Open the POST /posts request and add a test asserting the status code is 201, and a second test asserting the response body's title field matches the title you sent in the request body.
  5. Open the DELETE /posts/1 request and add a test asserting the status code is 200.
  6. Run the whole Posts folder using the Runner and confirm every test passes.

Expected outcome: Every request in the Posts folder has at least one meaningful assertion in its Tests tab, and running the folder with the Collection Runner shows all tests passing with a green result for each request.

Exercise 3: Run the Collection with Newman in a Script

In this exercise you move the collection you built and tested in the Postman UI onto the command line using Newman, which is the step that makes it possible to run your tests automatically rather than by clicking Send. You will install Newman, export your collection as a JSON file, and run it from a terminal, then generate an HTML report so the results can be shared with someone who was not at the keyboard. This exercise assumes Node.js and npm are already installed on your machine.

  1. Install Newman globally with npm install -g newman.
  2. In Postman, export your 'JSONPlaceholder Posts' collection as a Collection v2.1 JSON file.
  3. Open a terminal in the folder containing the exported file and run newman run JSONPlaceholder-Posts.postman_collection.json.
  4. Confirm the terminal output shows every request and every assertion passing, with a final summary table.
  5. Install the HTML reporter with npm install -g newman-reporter-htmlextra.
  6. Re-run the collection with the HTML reporter enabled and open the generated report in a browser to review the results visually.

Expected outcome: The collection built and tested earlier runs successfully from the command line with Newman, producing a console summary with zero failures and an HTML report file that can be opened in a browser and shared with a teammate who does not have Postman open.

Quiz

1. What is the main purpose of Newman in an API testing workflow?

  1. It replaces Postman as the tool used to build requests
  2. It runs a Postman collection from the command line, outside the Postman application
  3. It generates mock servers for an API automatically
  4. It converts a Postman collection into an OpenAPI specification
Show answer

B. It runs a Postman collection from the command line, outside the Postman application

Newman is Postman's command-line companion, built specifically to run an exported collection outside the Postman desktop application, which is what makes it possible to run that same collection automatically from a terminal or inside a continuous integration pipeline.

2. In Postman, what is the benefit of using a variable such as {{baseUrl}} instead of typing the full URL into every request?

  1. Variables make requests run faster over the network
  2. Variables are required by the HTTP specification for any request body
  3. Variables let the same collection run against different servers, such as local, staging and production, without editing every request
  4. Variables automatically add authentication headers to every request
Show answer

C. Variables let the same collection run against different servers, such as local, staging and production, without editing every request

A variable defined at the collection or environment level can be swapped by selecting a different environment, so the identical set of requests can target different servers without manually editing each request's URL.

3. Which Postman tab is used to write test scripts with functions such as pm.test and pm.expect?

  1. The Headers tab
  2. The Tests tab
  3. The Params tab
  4. The Authorization tab
Show answer

B. The Tests tab

The Tests tab in the request builder is where JavaScript test scripts are written using Postman's pm API, including pm.test for naming an assertion and pm.expect for the assertion itself, and these scripts run automatically after the response is received.

4. What does exporting a Postman collection as Collection v2.1 JSON allow you to do?

  1. Open the collection in a spreadsheet application
  2. Run the collection with Newman or import it on another machine
  3. Automatically deploy the API being tested
  4. Convert all requests into curl commands permanently
Show answer

B. Run the collection with Newman or import it on another machine

Exporting a collection as a JSON file is what produces a portable file that Newman can run from the command line, and that can also be imported back into Postman on another machine or shared with a teammate.

5. Why is it useful to add assertions on a response body's actual field values, such as checking a created post's title matches what was sent, rather than only checking the status code?

  1. Status codes are not reliable in modern APIs
  2. Checking only the status code can miss bugs where the server returns a success code but incorrect or incomplete data
  3. Field-level assertions run faster than status code assertions
  4. Postman does not allow status code checks without a field-level check first
Show answer

B. Checking only the status code can miss bugs where the server returns a success code but incorrect or incomplete data

A server can return a success status code such as 200 or 201 while still returning the wrong data, a missing field, or data that does not match what was submitted, so assertions on the actual body content catch classes of bugs that a status code check alone would miss.

Related docs

All courses