Prompt
How do I create reusable API test cases with variables?
Latest observation
Oct 6, 2026
OpenAI APIWeb search: off
A good way to create reusable API test cases with variables is to separate:
- the test flow (what you do)
- the data (what changes)
That lets you run the same test for many inputs without duplicating the whole case.
Common pattern
Use variables for things like:
- base URL
- endpoint paths
- auth tokens
- request body values
- expected status codes
- IDs captured from earlier responses
Example structure
- Setup: authenticate and save
token - Action: call endpoint using variables
- Assertion: check response using expected variables
Example in Postman
1) Define variables
You can store variables in:
- environment
- collection
- global
- data file
Example variables:
baseUrl = https://api.example.comtoken = ...userId = 123
2) Use variables in the request
GET {{baseUrl}}/users/{{userId}}
Authorization: Bearer {{token}}
3) Capture values from responses
In the Tests tab:
const json = pm.response.json();
pm.environment.set("userId", json.id);
4) Reuse the same test with different data
Use a CSV/JSON data file in Collection Runner/Newman:
[
{ "userId": "101", "expectedStatus": 200 },
{ "userId": "999", "expectedStatus": 404 }
]
Then reference them as:
GET {{baseUrl}}/users/{{userId}}
And assert:
pm.test("Status code matches", function () {
pm.response.to.have.status(parseInt(pm.iterationData.get("expectedStatus")));
});
Example in Python (pytest + requests)
If you’re automating tests in code, use parameterization.
import pytest
import requests
BASE_URL = "https://api.example.com"
@pytest.mark.parametrize("user_id, expected_status", [
(101, 200),
(999, 404),
])
def test_get_user(user_id, expected_status):
response = requests.get(f"{BASE_URL}/users/{user_id}")
assert response.status_code == expected_status
Reuse helper functions
def get_auth_token():
return "your-token"
def get_user(user_id):
token = get_auth_token()
return requests.get(
f"{BASE_URL}/users/{user_id}",
headers={"Authorization": f"Bearer {token}"}
)
Best practices for reusable API tests
- Keep test data separate from test logic
- Use descriptive variable names
- Parameterize endpoint-specific values
- Avoid hardcoding secrets
- Centralize auth and common headers
- Validate both success and failure cases
- Use setup/teardown for resources created during tests
- Capture dynamic IDs from earlier requests instead of hardcoding them
If you want maximum reuse
Consider a layered approach:
- test data files: inputs/expected results
- API client/helper layer: functions for each endpoint
- test layer: assertions and scenarios
Example:
api_client.py→create_user(),get_user()test_users.py→ parameterized teststestdata/users.json→ varied inputs
If you want, I can show you:
- a Postman example,
- a pytest example, or
- a generic template for reusable API tests.