A Python client library for the SparkTraffic API v2
Installation • Quick Start • API Reference • Examples • Contributing
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
- Python 3.8 or higher
- A SparkTraffic account with an API key
git clone https://github.com/nickleus27/sparktraffic-api-example.git
cd sparktraffic-api-example
pip install -r requirements.txtpip install -r requirements-dev.txtexport 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 keyfrom 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()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 closedAll API requests require an API key passed in the API_KEY header. The client handles this automatically:
client = SparkTrafficClient(api_key="your-api-key")| 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 |
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}")# 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)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)# 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")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}")| Value | Description |
|---|---|
TrafficType.DIRECT |
Direct traffic visits |
TrafficType.ORGANIC |
Organic search traffic |
TrafficType.REFERRAL |
Referral traffic from other sites |
TrafficType.SOCIAL |
Social media traffic |
| Value | Description |
|---|---|
GeoType.GLOBAL |
Global traffic (no targeting) |
GeoType.COUNTRIES |
Target specific countries |
GeoType.CITIES |
Target specific cities |
| 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 |
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.pysparktraffic-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
make testOr directly with pytest:
pytest tests/ -v --cov=src --cov-report=term-missingmake format # Auto-format with black
make lint # Check with ruff
make typecheck # Type check with mypymake all- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Please ensure all tests pass and code is formatted before submitting.
This project is licensed under the MIT License. See the LICENSE file for details.
- Website: https://www.sparktraffic.com
- Email: support@sparktraffic.com