Data-Driven API Testing: Run API Requests in a Loop with a CSV File

Log in as many users, chain a token into the next request, check every response with tests, and export the run as a Python script for CI.

Write the data file

Put one test case per row and give each column a header. The header becomes a variable name, so a column called email is used as {{email}} in the URL, headers or body. Quote a value that contains a comma, and keep the file in UTF-8.

A JSON array of objects works the same way and is easier when a value is itself a list or an object.

email,password,expectedStatus
[email protected],correct-horse,200
[email protected],wrong-password,401

Chain a token from one request to the next

In the API client, create a Login request that posts {{email}} and {{password}}, and a Profile request whose Auth tab uses a Bearer token of {{token}}. In the Login request's Tests script, save the token from the response so the next request in the same iteration can use it.

Test the status you expect for each row instead of always expecting 200, so the wrong-password row passes when the API correctly refuses it.

pm.test("Status matches the data file", () => {
  pm.expect(pm.response.code).to.eql(Number(pm.iterationData.get("expectedStatus")));
});

if (pm.response.code === 200) {
  pm.environment.set("token", pm.response.json().token);
}

Run every row with the collection runner

Open Run, choose the collection, and select the CSV file. With iterations left at 1, the runner performs one iteration per row: Login, then Profile, for each user. Each request shows its status, time and test results, and failed rows are highlighted so you can open the exact request that failed.

Add a delay between requests if the API rate-limits you, and turn on Stop at the first failure while you are still writing the tests.

Run the same tests in CI with Python

Switch the runner to Export as script and download the Python version. It needs only the requests package, reads the same CSV with --data, carries the token between requests like the browser run, and exits with an error code when a request fails, so a CI job fails too.

Pass environment-specific values with --var instead of editing the script, and keep secrets in your CI system's secret store rather than in the data file.

pip install requests
python run_collection.py --data users.csv --var baseUrl=https://staging.example.com --bail --report results.json

Reference: RFC 4180: Common Format and MIME Type for CSV Files.