Exceptions
Error types raised by StakeAPI β and how to handle them gracefully.
π‘ Don't have a Stake.com account yet? Sign up here to get started and unlock all API features.
Overview
All StakeAPI exceptions inherit from StakeAPIError, which itself inherits from Pythonβs built-in Exception. This hierarchy lets you catch errors at whatever granularity you need β catch every StakeAPI error with one except StakeAPIError block, or handle each case individually.
Import:
from stakeapi.exceptions import (
StakeAPIError,
AuthenticationError,
RateLimitError,
ValidationError,
NetworkError,
GameNotFoundError,
InsufficientFundsError,
)
Exception Hierarchy
Exception
βββ StakeAPIError # Base class β catch-all for library errors
βββ AuthenticationError # 401 / invalid token or session
βββ RateLimitError # 429 / too many requests
βββ ValidationError # Bad input values
βββ NetworkError # Connection / timeout failures
βββ GameNotFoundError # Requested game does not exist
βββ InsufficientFundsError # Balance too low for the operation
StakeAPIError
Base class for all StakeAPI exceptions. Catch this to handle any library error without caring about the specific cause.
class StakeAPIError(Exception):
pass
When raised:
- GraphQL response contains an
errorsfield - HTTP response is
4xxor5xxand no more specific exception applies - Cloudflare blocks the request (
403 Forbidden)
Example:
from stakeapi import StakeAPI
from stakeapi.exceptions import StakeAPIError
async with StakeAPI(access_token="...", cf_clearance="...") as client:
try:
balance = await client.get_user_balance()
except StakeAPIError as e:
print(f"API error: {e}")
# Log, retry, or alert
A
403response from Stake.com usually means yourcf_clearancecookie is expired or missing. Refresh it from your browser β see the Authentication Guide.
AuthenticationError
Raised when the API returns 401 Unauthorized β meaning your access token or session cookie is invalid, expired, or missing.
class AuthenticationError(StakeAPIError):
pass
When raised:
access_tokenis wrong, expired, or not provided for a protected endpoint- Session cookie is invalid or has been revoked
Example:
from stakeapi.exceptions import AuthenticationError
async with StakeAPI(access_token="bad_token", cf_clearance="...") as client:
try:
user = await client.get_user_profile()
except AuthenticationError:
print("Your token is invalid. Get a fresh one from Stake.com.")
# Re-extract token from browser DevTools
How to fix:
- Log into Stake.com
- Open DevTools (
F12) β Network tab - Find a
/_api/graphqlrequest - Copy the
x-access-tokenheader value - Pass it to
StakeAPI(access_token=...)
RateLimitError
Raised when the API returns 429 Too Many Requests β you are sending requests too fast.
class RateLimitError(StakeAPIError):
pass
When raised:
- More requests per second than Stake.com allows (typically ~10 req/s)
- Burst of requests in a short window
Example:
import asyncio
from stakeapi.exceptions import RateLimitError
async with StakeAPI(access_token="...", cf_clearance="...") as client:
try:
games = await client.get_casino_games()
except RateLimitError:
print("Rate limit hit β waiting 5 seconds...")
await asyncio.sleep(5)
games = await client.get_casino_games() # Retry
How to avoid:
- Set
rate_limitin the constructor (default is10req/s) - Add
await asyncio.sleep(0.1)between rapid sequential calls - Use batching where possible instead of many small calls
# Lower the rate limit to be safe
client = StakeAPI(
access_token="...",
cf_clearance="...",
rate_limit=5, # max 5 requests/second
)
ValidationError
Raised when input data does not meet the required format or constraints.
class ValidationError(StakeAPIError):
pass
When raised:
- A bet amount is below
min_betor abovemax_bet - A required parameter is missing or the wrong type
- An ID has an invalid format
Example:
from stakeapi.exceptions import ValidationError
from stakeapi.utils import validate_bet_amount
from decimal import Decimal
async with StakeAPI(access_token="...", cf_clearance="...") as client:
amount = Decimal("0.000000001") # Too small
try:
if not validate_bet_amount(amount, Decimal("0.00001"), Decimal("100")):
raise ValidationError(f"Bet amount {amount} is below the minimum.")
result = await client.dice_roll(float(amount), "btc", target=50.5)
except ValidationError as e:
print(f"Validation failed: {e}")
NetworkError
Raised when there is a low-level network problem β no response received, connection refused, or DNS failure.
class NetworkError(StakeAPIError):
pass
When raised:
aiohttp.ClientErrorβ wraps underlying network errors- Connection timeout (exceeds the
timeoutvalue set in the constructor) - DNS resolution failure
Example:
from stakeapi.exceptions import NetworkError
async with StakeAPI(access_token="...", cf_clearance="...", timeout=10) as client:
try:
balance = await client.get_user_balance()
except NetworkError as e:
print(f"Network problem: {e}")
print("Check your internet connection and try again.")
How to handle:
- Implement exponential backoff for retries
- Increase
timeoutif your connection is slow - Check for Stake.com maintenance on their Discord
GameNotFoundError
Raised when you request details for a game ID that does not exist on Stake.com.
class GameNotFoundError(StakeAPIError):
pass
When raised:
get_game_details(game_id)is called with an unknown or misspelled game ID
Example:
from stakeapi.exceptions import GameNotFoundError
async with StakeAPI(access_token="...", cf_clearance="...") as client:
try:
game = await client.get_game_details("nonexistent_game_xyz")
except GameNotFoundError:
print("That game doesn't exist. Try get_casino_games() to list valid IDs.")
InsufficientFundsError
Raised when the account balance is too low to complete an operation β typically when placing a bet.
class InsufficientFundsError(StakeAPIError):
pass
When raised:
- A bet method is called but the wallet balance is less than the bet amount
- The vault balance is not moved to available before betting
Example:
from stakeapi.exceptions import GraphQLError
# The bet methods do not raise InsufficientFundsError yet: the site's
# rejection arrives as a GraphQLError whose message explains why.
async with StakeAPI(cookie_file="cookie.txt", allow_betting=True) as client:
try:
result = await client.dice_roll(9999, "btc", target=50.5) # Way too much
except GraphQLError as e:
print(f"Bet rejected: {e}")
balance = await client.get_user_balance()
available_btc = balance["available"].get("btc", 0)
print(f"Not enough funds. Available BTC: {available_btc:.8f}")
Handling All Errors Together
For production code, catch errors from most to least specific:
import asyncio
from stakeapi import StakeAPI
from stakeapi.exceptions import (
AuthenticationError,
RateLimitError,
InsufficientFundsError,
GameNotFoundError,
NetworkError,
ValidationError,
StakeAPIError,
)
async def safe_place_bet(client, game_id: str, amount: float):
try:
bet = await client.dice_roll(amount, "btc", target=50.5)
print(f"Bet placed: {bet.get('id')} β payout {bet.get('payout')}")
return bet
except AuthenticationError:
print("Token expired β re-authenticate.")
except RateLimitError:
print("Rate limit hit β sleeping 5s...")
await asyncio.sleep(5)
return await safe_place_bet(client, game_id, amount)
except InsufficientFundsError:
print("Not enough balance.")
except GameNotFoundError:
print(f"Game '{game_id}' not found.")
except ValidationError as e:
print(f"Invalid input: {e}")
except NetworkError as e:
print(f"Network error: {e}")
except StakeAPIError as e:
print(f"Unexpected API error: {e}")
return None
Error Reference Table
| Exception | HTTP Status / Trigger | Common Fix |
|---|---|---|
StakeAPIError | Any unhandled API error | Check message for details |
AuthenticationError | 401 | Refresh access_token from browser |
RateLimitError | 429 | Back off and retry after delay |
ValidationError | Bad input | Validate with validate_bet_amount() etc. |
NetworkError | No response / timeout | Check connectivity, increase timeout |
GameNotFoundError | Unknown game ID | Use get_casino_games() for valid IDs |
InsufficientFundsError | Low balance | Check balance before betting |
π¬ Join the StakeAPI Community on Discord
Get help, share your projects, discuss strategies, and stay up to date with the latest StakeAPI news.
Join Our Discord Server ββοΈ Built with ChipaEditor
ChipaEditor is the ultimate code editor built for speed, simplicity, and power. Try it free today.
Try ChipaEditor Free βSee Also
- Error Handling Guide β Production-grade error handling patterns
- StakeAPI Client β Methods that raise these exceptions
- Authentication Guide β Fix
AuthenticationError - Rate Limiting Guide β Avoid
RateLimitError