Prompt
How do I parameterize API tests for different environments?
Latest observation
Oct 6, 2026
OpenAI APIWeb search: off
A good way to parameterize API tests across environments is to keep the test logic environment-agnostic and inject environment-specific values at runtime.
Common approach
1. Externalize environment config
Store things like:
- base URL
- auth token / client ID / secret
- tenant ID / region
- feature flags
in a config file or environment variables, for example:
# config/dev.yml
base_url: https://dev.api.example.com
auth_token: ${AUTH_TOKEN}
# config/staging.yml
base_url: https://staging.api.example.com
auth_token: ${AUTH_TOKEN}
2. Select environment at runtime
Pass the target environment when running tests:
ENV=staging pytest
or
mvn test -Denv=prod
3. Build tests around a fixture/helper
Load the right config once, then reuse it in tests:
import os
import pytest
import requests
@pytest.fixture(scope="session")
def env_config():
env = os.getenv("ENV", "dev")
configs = {
"dev": {"base_url": "https://dev.api.example.com"},
"staging": {"base_url": "https://staging.api.example.com"},
"prod": {"base_url": "https://api.example.com"},
}
return configs[env]
def test_health(env_config):
r = requests.get(f"{env_config['base_url']}/health")
assert r.status_code == 200
If you want the same test to run against multiple environments
Parameterize the environment itself:
import pytest
@pytest.mark.parametrize("base_url", [
"https://dev.api.example.com",
"https://staging.api.example.com",
])
def test_health(base_url):
r = requests.get(f"{base_url}/health")
assert r.status_code == 200
Best practices
- Don’t hardcode URLs or credentials in test code.
- Use environment variables for secrets.
- Keep one canonical test suite and vary only config.
- Separate tests that are safe for prod from destructive tests.
- Add timeouts/retries carefully, since environments may differ in latency.
- If using CI, define environment matrices like:
- dev
- staging
- pre-prod
Recommended pattern
For most teams:
- config files for non-secret settings
- environment variables / secrets manager for credentials
- fixtures or setup hooks to load config
- CI matrix to run the same suite in multiple environments
If you want, I can show you a concrete example in pytest, JUnit, Postman/Newman, or Playwright API testing.