Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 30 ยท Projects and Practice

Practice exercises with solutions

Eight hands-on Postman and API testing exercises on assertions, variables, chaining, negative tests and data-driven runs, each with a worked solution.

Reading about API testing teaches you the vocabulary. Writing tests teaches you the craft. This lesson gives you eight small exercises that cover the skills you have met in the track: assertions, variable scopes, chaining, negative tests, polling and data-driven runs. Each exercise states a task, gives a hint, and then shows a worked solution.

Try each task on your own first. Write your answer on paper or in the editor before you look at the solution; the effort is what makes the idea stick. The solutions are written as stand-ins: plain JavaScript that behaves like the Postman scripts you would write (pm.test, pm.expect, variables, a runner), so you can run and change them here. In real Postman the same logic lives in the Tests tab or the Pre-request Script tab, and the real pm object replaces the little helpers below.

What is real and what is not: the assertions, variable lookups and loops are the same logic you would write in Postman. The test and eq helpers, the fake responses and the fake API functions are written for this lesson. Real requests, the Collection Runner and Newman are not available on this site.

The solutions share two tiny helpers. They are repeated in every editor so each one runs on its own:

JavaScript
const test = (name, fn) => {
  try { fn(); console.log("PASS " + name); }
  catch (e) { console.log("FAIL " + name + " - " + e.message); }
};
const eq = (actual, expected) => {
  if (actual !== expected) throw new Error("expected " + expected + " but got " + actual);
};

Eight exercises, four skills

Assertions Exercises 1 to 3.
Variables Exercises 4 and 5.
Negative tests Exercise 6.
Loops and data Exercises 7 and 8.

Try each task before you open the solution.

1 / 2

Exercise 1: status, header and time

Task. A response arrives with status 200, a Content-Type header and a measured time of 180 ms. Write three tests: the status is 200, the content type contains application/json, and the response time is under 500 ms.

Hint. Header names are case-insensitive, so normalize them before you compare. In Postman you would use pm.response.to.have.status(200), pm.response.headers.get("Content-Type") and pm.response.responseTime.

JS Exercise 1 solution

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Exercise 2: checking a JSON body

Task. The body is a list of products. Write tests that check: the body is an array with at least one item, every product has a numeric price above zero, and every sku is unique.

Hint. Use every for "all items", and a Set to count unique values.

JS Exercise 2 solution

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Exercise 3: a mini schema check

Task. Write a function checkShape(value, shape) that compares an object with a description such as { id: "number", email: "string" } and returns a list of problems. Run it on one good and one bad response.

Hint. Loop over the keys of the shape and compare typeof. A missing key has type undefined, so it shows up as a mismatch. Real projects use JSON Schema for this, as in Contract testing and OpenAPI.

JS Exercise 3 solution

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Exercise 4: which variable wins?

Task. The same name, baseUrl, exists in five scopes. Write lookup(name) that returns the value from the most specific scope that has it. The order, from most to least specific, is local, data, environment, collection, global. Test it while removing scopes one at a time.

Hint. Keep the scopes in an array ordered from most to least specific, and return the first hit. See Environments and variables for the real rules.

JS Exercise 4 solution

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Exercise 5: chain a created id into the next request

Task. A fake API has createUser(body) and getUser(id). Create a user, save the new id in a variable, read the user back with that id, and assert that the name matches. Finally delete the user and assert that a second read returns 404.

Hint. The id comes from the response of the first call. Store it in a plain vars object, as you would in pm.collectionVariables.

JS Exercise 5 solution

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Exercise 6: negative tests

Task. The fake endpoint POST /transfer should answer 401 without a token, 422 when the amount is not a positive number, and 200 for a valid request. Write one test per case, and give each test a name that says what it expects.

Hint. A good API suite checks failures as carefully as successes. Tests that only prove "it works when everything is right" miss most real bugs.

JS Exercise 6 solution

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Exercise 7: poll until ready

Task. A job reports pending twice and then done. Write a loop that checks the status up to five times and stops as soon as the job is done. Print how many checks were needed, and make sure the loop cannot run forever.

Hint. In Postman this is the setNextRequest retry pattern from Chaining requests and workflows: count the attempts, repeat while the status is not final and the counter is below the limit.

JS Exercise 7 solution

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Exercise 8: a data-driven run

Task. You have a table of inputs and the status you expect for each: { qty: 1, expected: 200 }, { qty: 0, expected: 422 }, and so on. Write a loop that runs the fake endpoint once per row, prints PASS or FAIL for each row, and ends with a summary. One row has a wrong expectation on purpose, so you can see a failure.

Hint. This is what the Collection Runner does with a CSV or JSON file: it reads one row per iteration and exposes the columns as data variables. See The Collection Runner and data-driven testing.

JS Exercise 8 solution

Press Run (or Ctrl + Enter) to see the console output here.

No output.

How to review your own answers

When your solution differs from the one shown, that is fine. Check it against these questions instead of matching it line by line:

  • Does each test have one clear reason to fail, and a name that says what it checks?
  • Does the test fail when the API is wrong? Change the fake response and see whether the test notices.
  • Does a failing test print the actual value, so you do not need a debugger?
  • Did you clean up everything you created, and make loops finite?

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In exercise 4, which variable wins when the same name exists in the data scope and the collection scope?

    Postman resolves from the most specific scope: local, then data, environment, collection and finally global.
  2. 2. Why does exercise 6 test a wrong token as well as a missing token?

    A missing header and an invalid value are usually handled by different branches, so one passing does not prove the other.
  3. 3. What keeps the polling loop in exercise 7 from running forever?

    The loop condition checks both the status and the attempt count, so it ends after the limit even if the job never finishes.
  4. 4. In a data-driven run, what does each iteration use?

    The runner repeats the request once per row and exposes that row's columns to scripts and URLs.

Summary

  • Practice by writing tests that fail for the right reason and pass for the right reason.
  • Assertions cover status, headers, timing, body shape and uniqueness.
  • Variables resolve from the most specific scope outward; chaining saves a response value for the next request.
  • Negative tests (no token, bad token, invalid input) deserve as much care as happy paths.
  • Polling needs a limit, and data-driven runs turn one request into many checks.
  • The solutions here are plain JavaScript stand-ins; the real versions use the pm object inside Postman.

Next: Postman and API testing interview questions.