Skip to main content

Pytest API automation framework with custom HTML reporting, reusable fixtures, and fluent assertions

Project description

pytest-api-core

PyPI version Python License

A reusable pytest plugin for API automation — fluent assertions, built-in auth strategies, environment-aware configuration, and a self-contained HTML report.

Features

  • APIClientrequests.Session wrapper with retry, timeout, and structured logging
  • Fluent assertionsassert_that(response).status_is(200).json_path("$.id").equals(1) (json_path() supports a small dot/bracket-index subset, not full JSONPath — see docs/QUICKSTART.md; response_time_under() measures the whole request including any retries, not just the final attempt)
  • Auth strategies — Bearer token, Basic, API Key (header/query), OAuth2 client credentials (need something else, like an OAuth2 refresh-token flow or signed requests? subclass AuthBase — see docs/QUICKSTART.md)
  • Standalone assertion helpersassert_equal, assert_contains, assert_matches, assert_matches_schema, etc. for values outside an APIResponse — see docs/QUICKSTART.md
  • Configurable retry policy — max attempts, backoff factor, and retryable methods, overridable per environment (see below)
  • Environment config — Python settings.py classes + .env file + env var overrides
  • Custom HTML report — self-contained file with charts, filterable table, and request/response details
  • Auto-registered fixtures — zero boilerplate in consuming projects

Installation

pip install pytest-api-core==1.0.3

With .env file support (recommended):

pip install "pytest-api-core[dotenv]==1.0.3"

Quick start

# tests/test_posts.py
from pytest_api_core.assertions import assert_that

def test_get_post(api_client):
    response = api_client.get("/posts/1")
    assert_that(response).status_is(200).json_path("$.id").equals(1)

def test_create_post(api_client):
    payload = {"title": "foo", "body": "bar", "userId": 1}
    response = api_client.post("/posts", json=payload)
    assert_that(response).status_is(201).has_key("id")
pytest tests/ --api-env=staging

For full setup instructions — including pytest.ini, config/settings.py, conftest.py auth overrides, and CI integration — see docs/QUICKSTART.md.


Configuration

Resolution order (highest → lowest priority)

Priority Source
1 Shell / CI environment variables (API_BASE_URL, API_TOKEN, …)
2 --api-base-url CLI flag
3 ENVIRONMENTS[env] class in settings_module
4 Built-in defaults (http://localhost, timeout 30 s)

Retry policy

APIClient retries idempotent requests (GET, HEAD, OPTIONS) on 500/502/503/504 responses using urllib3.Retry. All three knobs follow the same env var → CLI flag → settings_module → built-in default precedence as base_url:

Setting settings_module attribute CLI flag Env var Default
Max retry attempts api_retry_total --api-retry-total API_RETRY_TOTAL 3
Backoff factor api_retry_backoff_factor --api-retry-backoff-factor API_RETRY_BACKOFF_FACTOR 0.3
Retryable methods api_retry_methods --api-retry-methods (comma-separated) API_RETRY_METHODS (comma-separated) GET,HEAD,OPTIONS

Backoff factor 0.3 produces sleeps of 0s, 0.3s, 0.6s, 1.2s, ... between attempts.

Example — a flakier staging environment gets more retries and a longer backoff:

# settings.py
class StagingSettings(BaseSettings):
    base_url = "https://api.staging.mycompany.com"
    api_retry_total = 5
    api_retry_backoff_factor = 1.0

Or per-run, without touching code:

pytest tests/ --api-env=staging --api-retry-total=5 --api-retry-backoff-factor=1.0

To disable retries entirely, pass retry=None directly when constructing an APIClient yourself (not available as a config option, since "no retries" isn't something you'd want to toggle per environment).

Key pytest.ini options

Option Description Default
api_env Active environment name dev
api_settings_module Dotted path to your settings module
api_dotenv_file Path to .env file .env
api_log_level Framework log level WARNING
api_html_report HTML report path (supports {env}, {timestamp})
api_html_theme Report theme: light or dark dark
api_html_title Report browser tab title API Test Report
api_html_header Report page header text API Test Report

CLI flags

Flag Description
--api-env Override active environment
--api-base-url Override base_url
--api-log-level Override framework log level
--api-html-report Override HTML report path
--api-retry-total Override max retry attempts (default: 3)
--api-retry-backoff-factor Override retry backoff factor (default: 0.3)
--api-retry-methods Override retryable HTTP methods, comma-separated (default: GET,HEAD,OPTIONS)

Fixtures

All fixtures are auto-registered — no imports needed in conftest.py.

Fixture Scope Description
api_config session Resolved config dict for the active env
auth_provider session Auth strategy passed to api_client — override this alone to swap auth
api_client session Configured APIClient instance, depends on auth_provider
api_bearer_auth function BearerAuth from API_TOKEN env var
api_basic_auth function BasicAuth from API_USERNAME / API_PASSWORD
api_key_auth function APIKeyAuth from API_KEY_NAME / API_KEY_VALUE

Override auth_provider in your project's conftest.py to inject custom auth without redeclaring api_client — see docs/QUICKSTART.md.


License

See LICENSE.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pytest_api_core-1.0.3.tar.gz (34.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pytest_api_core-1.0.3-py3-none-any.whl (38.4 kB view details)

Uploaded Python 3

File details

Details for the file pytest_api_core-1.0.3.tar.gz.

File metadata

  • Download URL: pytest_api_core-1.0.3.tar.gz
  • Upload date:
  • Size: 34.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.15

File hashes

Hashes for pytest_api_core-1.0.3.tar.gz
Algorithm Hash digest
SHA256 1cce6a0a2ee1d64c1e1fc1b00c8bd51ae1ff93f4042869ba0e22a9815faa6116
MD5 8cd5664a1b53c922237af4cb2d70a442
BLAKE2b-256 b0b0ffd32479242c3f621e99c058800cb791402ef173b0ddd923c0259b65dd14

See more details on using hashes here.

File details

Details for the file pytest_api_core-1.0.3-py3-none-any.whl.

File metadata

File hashes

Hashes for pytest_api_core-1.0.3-py3-none-any.whl
Algorithm Hash digest
SHA256 84459328eac2a6ded5c31420e605e044f73dca4dc8b75e397b818f12022e3631
MD5 af3067c759bd97fc8ca2d9577e33557b
BLAKE2b-256 b274d7e584d6c6dce5ee50c8e8b7496cb00941473d8c9650e9594df398bb5284

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page