Lesson 1 — Betfair: Environment & sandbox setup
Get your Python environment ready, create a Betfair sandbox/test account, and run a short smoke test. This lesson prepares you to follow the Betfair track tutorials.
Prerequisites
- Python 3.10+ installed
- Basic familiarity with the command line
- An editor (VS Code, PyCharm) and optional git
- A Betfair developer/sandbox account (we use sandbox endpoints in examples)
Download software & tools (links)
Download the recommended tools below. Each link opens the official download page in a new tab.
pip install python-dotenv to manage environment variables.Create sandbox / developer credentials
Sign up for Betfair developer/sandbox access and obtain your API key and any test tokens. Official docs and signup pages:
Keep credentials in environment variables or a .env file. Example .env (never commit):
# .env (example — DO NOT COMMIT)
BETFAIR_API_URL=https://sandbox-api.example.com
BETFAIR_API_KEY=your_api_key_here
BETFAIR_USERNAME=test_user
BETFAIR_PASSWORD=test_pass
Free delayed/read‑only API: If you only need market data for experimentation (no order placement), Betfair offers a delayed/read‑only data feed useful for testing market lookups and UI work. Use a delayed key for read-only data and switch to sandbox/trading credentials when you need order placement. See the developer hub above for details.
Minimal authentication & request helper
Save this as auth.py. It demonstrates loading env vars and making a simple authenticated request to the sandbox. Replace API_URL and headers to match your provider’s docs.
import os
import requests
from dotenv import load_dotenv
load_dotenv()
API_URL = os.getenv('BETFAIR_API_URL', 'https://sandbox-api.example.com')
API_KEY = os.getenv('BETFAIR_API_KEY', '')
def headers():
return {
'X-Application': API_KEY,
'Content-Type': 'application/json'
}
def get_markets(search):
params = {'filter': search}
r = requests.get(f"{API_URL}/markets", headers=headers(), params=params, timeout=10)
r.raise_for_status()
return r.json()
if __name__ == '__main__':
try:
markets = get_markets('Match Odds')
print('Markets response keys:', markets.keys() if isinstance(markets, dict) else type(markets))
except Exception as e:
print('API error:', e)
Run python auth.py to validate connectivity. Expect JSON or a clear HTTP error (401/403 if keys incorrect).
Quick market lookup example
This snippet calls the helper above to list markets and print the first market name and id.
from auth import get_markets
markets = get_markets('Match Odds')
if markets:
# provider responses vary — inspect structure
first = markets[0] if isinstance(markets, list) and markets else markets
print('Found market:', first.get('name') if isinstance(first, dict) else first)
Validation: If no markets are returned, verify API_URL, API_KEY, and network connectivity. If you see 401/403, double-check credentials and sandbox permissions.
Safety & next steps
- Always use sandbox/test credentials for development — never use production keys.
- Store secrets in environment variables or a secrets manager; rotate keys periodically.
- Be mindful of Betfair rules: stake increments, minimums, and market suspensions.
Security: Protect webhooks with HMAC or a shared secret; use HTTPS. Add idempotency tokens on order requests to avoid duplicate orders.
What you’ll build next
Lesson 2 will implement a full auth wrapper with token refresh and a resilient request function that retries on transient errors. After that we’ll look up markets and place test orders in Lesson 4.
