Python Logo

Python Examples

Ready-to-use Python code for integrating CaptchaKings API.

🎉 NEW! Official Python library now available on PyPI!
Install with: pip install captchakings
View on PyPI →
📦 Requirements: Python 3.6+

🚀 Quick Start (Recommended)

The easiest way to use CaptchaKings API is with our official library:

bash
pip install captchakings

Simple Example (3 lines of code!)

python
from captchakings import CaptchaKings

client = CaptchaKings('ck_your_api_key_here')
result = client.solve('captcha.jpg')

print(f"Solved: {result['prediction']}")
print(f"Confidence: {result['confidence']}")
print(f"Credits Remaining: {result['credits_remaining']}")

With Error Handling

python
from captchakings import CaptchaKings
from captchakings.exceptions import (
    AuthenticationError,
    InsufficientCreditsError,
    InvalidImageError
)

client = CaptchaKings('ck_your_api_key_here')

try:
    result = client.solve('captcha.jpg')
    print(f"✅ Solved: {result['prediction']}")
    print(f"Confidence: {result['confidence']}")
    
except AuthenticationError:
    print("❌ Invalid API key")
except InsufficientCreditsError:
    print("❌ Not enough credits")
except InvalidImageError:
    print("❌ Invalid image file")
except Exception as e:
    print(f"❌ Error: {e}")

With Automatic Retry

python
from captchakings import CaptchaKings

client = CaptchaKings('ck_your_api_key_here')

# Automatically retry up to 5 times on failure
result = client.solve_with_retry(
    'captcha.jpg',
    max_retries=5,
    retry_delay=2
)

print(f"Solved: {result['prediction']}")

Batch Processing

python
from captchakings import CaptchaKings
import os

# Use context manager for automatic cleanup
with CaptchaKings('ck_your_api_key_here') as client:
    captcha_folder = 'captchas/'
    
    for filename in os.listdir(captcha_folder):
        if filename.endswith(('.jpg', '.png')):
            filepath = os.path.join(captcha_folder, filename)
            
            try:
                result = client.solve_with_retry(filepath)
                print(f"✅ {filename}: {result['prediction']}")
            except Exception as e:
                print(f"❌ {filename}: {e}")
💡 Why use the library?
  • 93% less code - Just 3 lines vs 40+ lines
  • Automatic error handling - Built-in exception types
  • Retry logic - No need to implement yourself
  • Type hints - Better IDE autocomplete
  • Session reuse - Faster for multiple requests
  • Well tested - Production ready

📝 Manual Implementation (Without Library)

If you prefer not to use the library, here's how to implement it manually:

Installation

bash
pip install requests

Basic Example

python
import requests

def solve_captcha(api_key, image_path):
    url = 'https://captchakings.com/api/process.php'
    
    headers = {
        'Authorization': f'Bearer {api_key}'
    }
    
    with open(image_path, 'rb') as f:
        files = {
            'captcha': ('captcha.jpg', f, 'image/jpeg')
        }
        
        response = requests.post(url, headers=headers, files=files)
    
    if response.status_code == 200:
        data = response.json()
        
        if data['success']:
            return {
                'success': True,
                'prediction': data['data']['prediction'],
                'confidence': data['data']['confidence'],
                'credits_remaining': data['credits']['credits_remaining']
            }
        else:
            return {
                'success': False,
                'error': data.get('error', 'Unknown error')
            }
    else:
        return {
            'success': False,
            'error': f'HTTP {response.status_code}: {response.text}'
        }

# Usage
if __name__ == '__main__':
    API_KEY = 'ck_your_api_key_here'
    IMAGE_PATH = '/path/to/captcha.jpg'
    
    result = solve_captcha(API_KEY, IMAGE_PATH)
    
    if result['success']:
        print(f"✅ CAPTCHA Solved: {result['prediction']}")
        print(f"Confidence: {result['confidence']}")
        print(f"Credits Remaining: {result['credits_remaining']}")
    else:
        print(f"❌ Error: {result['error']}")

Complete Example with Error Handling

python
#!/usr/bin/env python3
"""
CaptchaKings API Client
Production-ready implementation with error handling
"""

import requests
import os
from typing import Dict, Optional

class CaptchaKingsAPI:
    def __init__(self, api_key: str):
        self.api_key = api_key
        self.base_url = 'https://captchakings.com/api/process.php'
        
    def solve(self, image_path: str) -> Dict:
        """
        Solve CAPTCHA from image file
        
        Args:
            image_path: Path to CAPTCHA image
            
        Returns:
            dict: API response
        """
        # Validate file
        if not os.path.exists(image_path):
            return {
                'success': False,
                'error': f'File not found: {image_path}'
            }
        
        # Prepare request
        headers = {
            'Authorization': f'Bearer {self.api_key}'
        }
        
        try:
            with open(image_path, 'rb') as f:
                files = {
                    'captcha': ('captcha.jpg', f, 'image/jpeg')
                }
                
                response = requests.post(
                    self.base_url,
                    headers=headers,
                    files=files,
                    timeout=30
                )
            
            # Parse response
            data = response.json()
            
            # Add HTTP status
            data['http_code'] = response.status_code
            
            return data
            
        except requests.exceptions.Timeout:
            return {
                'success': False,
                'error': 'Request timeout after 30 seconds'
            }
        except requests.exceptions.ConnectionError as e:
            return {
                'success': False,
                'error': f'Connection error: {str(e)}'
            }
        except requests.exceptions.RequestException as e:
            return {
                'success': False,
                'error': f'Request error: {str(e)}'
            }
        except ValueError as e:
            return {
                'success': False,
                'error': f'Invalid JSON response: {str(e)}'
            }

# Usage Example
if __name__ == '__main__':
    api = CaptchaKingsAPI('ck_your_api_key_here')
    result = api.solve('/path/to/captcha.jpg')
    
    if result.get('success'):
        print("✅ SUCCESS!")
        print("━" * 50)
        print(f"Prediction:        {result['data']['prediction']}")
        print(f"Confidence:        {result['data']['confidence']}")
        print(f"Process Time:      {result['data']['process_time']}s")
        print("━" * 50)
        print(f"Credits Deducted:  {result['credits']['credits_deducted']}")
        print(f"Credits Remaining: {result['credits']['credits_remaining']}")
        print(f"Plan:              {result['credits']['plan']}")
    else:
        print("❌ ERROR!")
        print(f"Error: {result.get('error', 'Unknown error')}")

Class with Retry Logic

python
import requests
import time

class CaptchaKingsClient:
    def __init__(self, api_key, max_retries=3):
        self.api_key = api_key
        self.base_url = 'https://captchakings.com/api/process.php'
        self.max_retries = max_retries
    
    def solve(self, image_path):
        for attempt in range(self.max_retries):
            result = self._make_request(image_path)
            
            if result['success']:
                return result
            
            # Don't retry on auth/credit errors
            error = result.get('error', '')
            if 'Invalid API key' in error or 'Insufficient credits' in error:
                return result
            
            if attempt < self.max_retries - 1:
                print(f"Attempt {attempt + 1} failed, retrying...")
                time.sleep(2)
        
        return result
    
    def _make_request(self, image_path):
        try:
            headers = {'Authorization': f'Bearer {self.api_key}'}
            
            with open(image_path, 'rb') as f:
                files = {'captcha': f}
                response = requests.post(
                    self.base_url,
                    headers=headers,
                    files=files,
                    timeout=30
                )
            
            return response.json()
            
        except Exception as e:
            return {
                'success': False,
                'error': str(e)
            }

# Usage
client = CaptchaKingsClient('ck_your_api_key_here')
result = client.solve('/path/to/captcha.jpg')

Async/Await Example (with aiohttp)

python
import aiohttp
import asyncio

async def solve_captcha_async(api_key, image_path):
    url = 'https://captchakings.com/api/process.php'
    headers = {'Authorization': f'Bearer {api_key}'}
    
    with open(image_path, 'rb') as f:
        data = aiohttp.FormData()
        data.add_field('captcha', f, filename='captcha.jpg')
        
        async with aiohttp.ClientSession() as session:
            async with session.post(url, headers=headers, data=data) as response:
                return await response.json()

# Usage
async def main():
    result = await solve_captcha_async('ck_your_api_key_here', '/path/to/captcha.jpg')
    print(result)

asyncio.run(main())

📚 More Resources

📦 PyPI Package

Official Python library

View on PyPI →

📖 Documentation

Complete API reference

View Docs →

💻 Other Languages

Node.jscURL

💡 Need Help?
Have questions or issues? Contact us at support@captchakings.com