REST API Testing Fundamentals
Setting up pytest and the requests library
Reading18 min read
Setting Up pytest and the requests Library
A clean virtual environment and a well-structured project prevent dependency conflicts and make onboarding new contributors painless.
Create a Virtual Environment
python -m venv .venv
source .venv/bin/activate # macOS/Linux
.venv\Scripts\activate # Windows
pip install pytest requests pytest-html
pip freeze > requirements.txt
Project Structure
api-tests/
├── conftest.py ← shared fixtures
├── pytest.ini ← pytest config
├── requirements.txt
└── tests/
├── test_users.py
├── test_orders.py
└── test_auth.py
pytest.ini — Baseline Configuration
[pytest]
base_url = https://api.example.com
testpaths = tests
addopts = -v --tb=short
Your First Request with the requests Library
import requests
response = requests.get('https://jsonplaceholder.typicode.com/posts/1')
print(response.status_code) # 200
print(response.json()) # dict
print(response.headers['Content-Type'])
Key requests Methods
| Method | Usage |
|---|---|
requests.get(url, params={}) | Query string params |
requests.post(url, json={}) | JSON body |
requests.put(url, json={}) | Replace resource |
requests.patch(url, json={}) | Partial update |
requests.delete(url) | Delete |
Always use the json= parameter for JSON bodies — not data=. Using json= automatically sets Content-Type: application/json.
A Session for Shared Headers
session = requests.Session()
session.headers.update({
'Authorization': 'Bearer my-token',
'Accept': 'application/json',
})
response = session.get('https://api.example.com/me')
A Session persists headers (and cookies) across requests. Use it in tests so every request automatically carries authentication headers.