PyApiBasics is a lightweight API test automation framework written in Python using PyTest. It provides a small, opinionated test harness and example tests that demonstrate common HTTP operations (GET, POST, PUT, PATCH, DELETE) against a REST API. The project is intended as a starting point for building automated API test suites.
Key features
- Simple utilities for common tasks (date/time helpers, base64 helpers, UUIDs) in
libs. - A compact
ApiOperationshelper inlibs/api_ops.pyfor making HTTP requests and handling common logging/serialization concerns. - Centralized configuration in
config/config.iniand small helper inlibs/config_ops.py. - Centralized logging to a root-level
automation.logwith rotation and automatic redaction of sensitive values. - A deterministic test mode (tests mock HTTP) so local runs are reliable and repeatable.
libs/- library code used by tests (api operations, config helpers, common utilities, logging config).config/- configuration files (e.g.config.ini).tests/- pytest test cases andconftest.pyfixtures.
- Tests import helpers from
libsand read configuration fromconfig/config.inivialibs/config_ops.py. ApiOperationsbuilds and issues HTTP requests usingrequests.Session. By default it attaches the configured API key as thex-api-keyheader.- Logging is centralized in
libs/logging_config.py. All modules useget_logger(__name__)to obtain a child logger under the project loggerPyApiBasics. - Logs are written to
automation.logat the repository root using a rotating file handler, and sensitive fields (API keys, tokens, passwords, email addresses) are redacted automatically before writing. - During test runs,
tests/conftest.pycan run a session-scoped fixture that monkeypatchesrequests.Session.requestto return canned responses for the sample tests — this makes test runs deterministic and avoids reliance on external services.
Requirements: Python 3.10 or newer.
- Clone the repository:
git clone https://github.com/chinmaymudholkar/PyApiBasics.git
cd PyApiBasics- Create and activate a virtual environment:
python -m venv .venv
# Linux / macOS
source .venv/bin/activate
# Windows (PowerShell)
# .venv\Scripts\Activate.ps1- Install dependencies:
pip install -r requirements.txt- Verify setup (run only the setup checks):
pytest -m setup -qPrimary configuration is stored in config/config.ini.
Example config/config.ini values used by the framework:
[common]
project_name = PYAPIBASICS
environment = TEST
api_key = reqres-free-v1
[base_urls]
TEST = https://reqres.inapi_key: A generic API key (default:reqres-free-v1) will be attached automatically to requests as thex-api-keyheader byApiOperations.- Environment override: you can set the API key via environment variables
REQRES_API_KEYorAPI_KEY.libs/config_ops.get_api_key()gives priority toREQRES_API_KEY, thenAPI_KEY, then theconfig.inivalue. For security prefer environment variables or secret stores for production.
- Log file:
automation.login the project root. - Implemented in
libs/logging_config.pyas a centralizedPyApiBasicslogger. Child loggers are created withget_logger(__name__). - Log rotation: a
RotatingFileHandleris configured withmaxBytes=5*1024*1024andbackupCount=5. - Redaction: the logger masks sensitive keys (default set includes
authorization,x-api-key,api_key,password,token,access_token,email) when logging headers or bodies. The redact behavior can be adjusted inlibs/logging_config.pyby modifyingSENSITIVE_KEYSor theredact()helper.
- Test files live in
tests/and use pytest markers:setup,get,post,delete,put,patch. - The test suite includes a
tests/conftest.pyfile that provides useful fixtures:- A session-scoped autouse fixture that (by default in this repo) monkeypatches
requests.Session.requestto return canned responses for the sample tests. This yields deterministic tests that do not depend on the network. - An autouse fixture that logs every test START and END and logs exception stacktraces when tests fail.
- A session-scoped autouse fixture that (by default in this repo) monkeypatches
Running tests
- Run all tests:
pytest -q- Toggle request mocking (deterministic tests) via environment variable
USE_MOCK_REQUESTS:
# default (mocking enabled)
export USE_MOCK_REQUESTS=true
pytest -q
# disable mocking -> tests will make real HTTP requests
export USE_MOCK_REQUESTS=false
pytest -q- Run tests for a specific marker, for example GET tests:
pytest -m get -q- Re-run a failing test (verbose output):
pytest tests/test_1_get.py::Test_Get::test_get_002 -q -r aView logs
- Tail the log while running tests:
tail -f automation.log- Show last N lines:
tail -n 200 automation.log- The real
reqres.inAPI may require an API key or change behavior. To avoid flakiness and to make local development fast and repeatable, the repository's tests are set up to run in deterministic mode (see the_mock_requestsfixture intests/conftest.py). - To exercise the real API:
- Remove or edit the
_mock_requestsfixture intests/conftest.py(it is session-scoped). After removal the tests will make real HTTP requests. - Ensure the
api_keyinconfig/config.iniis set to a valid value or modifylibs/config_ops.pyto read the key from an environment variable.
- Remove or edit the
- Add or change redacted keys: edit
SENSITIVE_KEYSinlibs/logging_config.py. - Adjust rotation size/retention: modify
RotatingFileHandlersettings inlibs/logging_config.py. - Toggle deterministic tests: modify or gate the
_mock_requestsfixture intests/conftest.py(e.g. based on an environment variable). - Move API key to environment: change
libs/config_ops.pyto preferos.environ.get("API_KEY")and update README with instructions.
- If tests fail with 401/Unauthorized during a live run, check that
config/config.inior your environment contains a valid API key and consider running in the deterministic mocked mode for development. - Use
automation.logto inspect detailed request/response logs and stacktraces for failures. Sensitive values will be redacted.
Contributions welcome — open an issue or PR with improvements. See LICENSE for license terms.