Skip to content

Repository files navigation

SparkTraffic API Client

A Python client library for the SparkTraffic API v2

Installation • Quick Start • API Reference • Examples • Contributing


Overview

This repository provides a clean, well-documented Python client for the SparkTraffic API v2. It demonstrates best practices for API integration, including proper authentication, error handling, data modeling, and resource management.

Features:

  • Full coverage of all SparkTraffic API v2 endpoints
  • Type-safe data models with Python dataclasses and enums
  • Comprehensive error handling with custom exceptions
  • Context manager support for automatic resource cleanup
  • Fully tested with pytest (unit tests included)
  • CI/CD pipeline with GitHub Actions

Requirements

  • Python 3.8 or higher
  • A SparkTraffic account with an API key

Installation

From Source

git clone https://github.com/nickleus27/sparktraffic-api-example.git
cd sparktraffic-api-example
pip install -r requirements.txt

For Development

pip install -r requirements-dev.txt

Quick Start

1. Set Your API Key

export SPARKTRAFFIC_API_KEY="your-api-key-here"

Or create a .env file based on the provided template:

cp .env.example .env
# Edit .env and add your API key

2. Basic Usage

from src import SparkTrafficClient

# Initialize the client
client = SparkTrafficClient(api_key="your-api-key")

# Check your account balance
balance = client.get_balance()
print(f"Economy credits: {balance.economy}")
print(f"Professional credits: {balance.professional}")
print(f"Expert credits: {balance.expert}")

# List all projects
project_ids = client.get_all_projects()
print(f"You have {len(project_ids)} projects")

# Always close the client when done
client.close()

3. Using the Context Manager (Recommended)

from src import SparkTrafficClient

with SparkTrafficClient(api_key="your-api-key") as client:
    balance = client.get_balance()
    projects = client.get_all_projects()
# Session is automatically closed

API Reference

Authentication

All API requests require an API key passed in the API_KEY header. The client handles this automatically:

client = SparkTrafficClient(api_key="your-api-key")

Available Methods

Method Description Returns
get_balance() Get account credit balance Balance
is_demo_allowed(url) Check if demo is available for a URL bool
get_all_projects(filters?) List all project IDs List[str]
get_project(unique_id) Get project details WebsiteTrafficProject
create_project(project) Create a new project str (new ID)
modify_project(project) Update an existing project bool
get_project_stats(from, to, id?) Get historical statistics dict
get_project_realtime_stats(id?) Get real-time statistics dict

Creating a Project

from src import SparkTrafficClient
from src.models import WebsiteTrafficProject, TrafficType, GeoType, TimeOnPage

client = SparkTrafficClient(api_key="your-api-key")

project = WebsiteTrafficProject(
    title="My Website Campaign",
    urls_1="https://example.com\nhttps://example.com/about",
    urls_2="https://example.com/services",
    traffic_type=TrafficType.ORGANIC,
    keywords="web traffic\nSEO visitors",
    speed=50,
    bounce_rate=35,
    return_rate=20,
    time_on_page=TimeOnPage.THIRTY_SEC,
    desktop_rate=60,
    geo_type=GeoType.COUNTRIES,
    geo="US,GB,CA",
    languages="en-US\nen-GB",
)

new_id = client.create_project(project)
print(f"Created project: {new_id}")

Modifying a Project

# Fetch existing project
project = client.get_project("your-project-id")

# Update fields
project.speed = 75
project.bounce_rate = 25
project.time_on_page = TimeOnPage.ONE_MIN

# Save changes
client.modify_project(project)

Filtering Projects

from src.models import ProjectFilter

filters = [
    ProjectFilter(field="title", operator="contain", value="campaign"),
    ProjectFilter(field="traffic_type", operator="equal", value="organic"),
]

project_ids = client.get_all_projects(filters=filters)

Getting Statistics

# Historical stats (last 30 days)
stats = client.get_project_stats(
    from_date="2024-01-01",
    to_date="2024-01-31",
    unique_id="your-project-id",
)

# Real-time stats
realtime = client.get_project_realtime_stats(unique_id="your-project-id")

Error Handling

from src import SparkTrafficClient, SparkTrafficError
from src.exceptions import AuthenticationError, BadRequestError, RateLimitError

try:
    client = SparkTrafficClient(api_key="your-key")
    balance = client.get_balance()
except AuthenticationError:
    print("Invalid API key")
except BadRequestError as e:
    print(f"Bad request: {e.message} (method: {e.method})")
except RateLimitError:
    print("Rate limit exceeded, please wait")
except SparkTrafficError as e:
    print(f"API error: {e}")

Data Models

TrafficType

Value Description
TrafficType.DIRECT Direct traffic visits
TrafficType.ORGANIC Organic search traffic
TrafficType.REFERRAL Referral traffic from other sites
TrafficType.SOCIAL Social media traffic

GeoType

Value Description
GeoType.GLOBAL Global traffic (no targeting)
GeoType.COUNTRIES Target specific countries
GeoType.CITIES Target specific cities

TimeOnPage

Value Duration
TimeOnPage.FIVE_SEC 5 seconds
TimeOnPage.THIRTY_SEC 30 seconds (default)
TimeOnPage.ONE_MIN 1 minute
TimeOnPage.TWO_MIN 2 minutes
TimeOnPage.THREE_MIN 3 minutes
TimeOnPage.FOUR_MIN 4 minutes
TimeOnPage.FIVE_MIN 5 minutes

Examples

The examples/ directory contains ready-to-run scripts:

File Description
basic_usage.py Check balance and list projects
manage_projects.py Create, modify, and filter projects
get_statistics.py Retrieve historical and real-time stats
context_manager.py Best practice: using context managers

Run any example:

export SPARKTRAFFIC_API_KEY="your-api-key"
python examples/basic_usage.py

Project Structure

sparktraffic-api-example/
├── src/
│   ├── __init__.py          # Package exports
│   ├── client.py            # Main API client class
│   ├── models.py            # Data models (dataclasses & enums)
│   └── exceptions.py        # Custom exception classes
├── examples/
│   ├── basic_usage.py       # Basic usage example
│   ├── manage_projects.py   # Project management example
│   ├── get_statistics.py    # Statistics retrieval example
│   └── context_manager.py   # Context manager example
├── tests/
│   ├── __init__.py
│   └── test_client.py       # Unit tests
├── docs/
│   └── api_reference.md     # Detailed API reference
├── .github/
│   └── workflows/
│       └── ci.yml           # GitHub Actions CI pipeline
├── .env.example             # Environment variable template
├── .gitignore               # Git ignore rules
├── LICENSE                  # MIT License
├── Makefile                 # Development commands
├── pyproject.toml           # Project metadata & tool config
├── requirements.txt         # Production dependencies
├── requirements-dev.txt     # Development dependencies
└── README.md                # This file

Development

Running Tests

make test

Or directly with pytest:

pytest tests/ -v --cov=src --cov-report=term-missing

Code Formatting

make format    # Auto-format with black
make lint      # Check with ruff
make typecheck # Type check with mypy

Run All Checks

make all

Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Please ensure all tests pass and code is formatted before submitting.

License

This project is licensed under the MIT License. See the LICENSE file for details.

Support

About

SparkTraffic API Python client example

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages