Installation
pip install fastcaptcha-api
Basic Usage
from fastcaptcha import FastCaptcha
# Initialize with your API key
client = FastCaptcha(api_key="your_api_key_here")
# Solve from file
result = client.solve('captcha.png')
print(f"Text: {result['text']}")
print(f"Confidence: {result['confidence']}")
print(f"Credits Remaining: {result['credits_remaining']}")
# Solve from URL
result = client.solve_url('https://example.com/captcha.png')
print(f"Text: {result['text']}")
# Solve from base64
import base64
with open('captcha.png', 'rb') as f:
base64_image = base64.b64encode(f.read()).decode('utf-8')
result = client.solve_base64(base64_image)
print(f"Text: {result['text']}")
Advanced Options
from fastcaptcha import FastCaptcha
client = FastCaptcha(
api_key="your_api_key_here",
api_url="https://fastcaptcha.org/api/v1/ocr/", # Custom API URL (optional)
timeout=30 # Request timeout in seconds (default: 30)
)
# Case-insensitive solving
result = client.solve('captcha.png', case_sensitive=False)
# Get detailed response
result = client.solve('captcha.png')
print(f"Text: {result['text']}")
print(f"Confidence: {result['confidence']:.2%}")
print(f"Model Used: {result['model_used']}")
print(f"Processing Time: {result['processing_time']:.3f}s")
print(f"Credits Remaining: {result['credits_remaining']}")
print(f"ML Available: {result['ml_available']}")
Error Handling
from fastcaptcha import FastCaptcha, FastCaptchaError
client = FastCaptcha(api_key="your_api_key_here")
try:
result = client.solve('captcha.png')
print(f"Solved: {result['text']}")
except FastCaptchaError as e:
print(f"Error: {e}")
# Handle specific errors
if "insufficient credits" in str(e).lower():
print("Please purchase more credits!")
elif "invalid api key" in str(e).lower():
print("Please check your API key!")
except Exception as e:
print(f"Unexpected error: {e}")
Batch Processing
from fastcaptcha import FastCaptcha
import os
client = FastCaptcha(api_key="your_api_key_here")
# Process multiple images
captcha_dir = 'captchas/'
for filename in os.listdir(captcha_dir):
if filename.endswith(('.png', '.jpg', '.jpeg')):
filepath = os.path.join(captcha_dir, filename)
try:
result = client.solve(filepath)
print(f"{filename}: {result['text']} (confidence: {result['confidence']:.2%})")
except FastCaptchaError as e:
print(f"{filename}: Error - {e}")
Benefits of Using the PyPI Package:
- ✅ Simple and clean API interface
- ✅ Built-in error handling
- ✅ Support for file, URL, and base64 inputs
- ✅ Automatic request retries
- ✅ Type hints for better IDE support
- ✅ Comprehensive documentation included
File Upload Method
import requests
url = "https://fastcaptcha.org/api/v1/ocr/"
headers = {"X-API-Key": "your_api_key_here"}
files = {"image": open("captcha.png", "rb")}
response = requests.post(url, headers=headers, files=files)
result = response.json()
print(f"Text: {result['text']}")
print(f"Confidence: {result['confidence']}")
print(f"Credits Remaining: {result['credits_remaining']}")
Base64 Method (Recommended)
import requests
import base64
# Read and encode image
with open("captcha.png", "rb") as f:
base64_image = base64.b64encode(f.read()).decode('utf-8')
url = "https://fastcaptcha.org/api/v1/ocr/"
headers = {
"Content-Type": "application/json",
"X-API-Key": "your_api_key_here"
}
data = {
"base64_image": f"data:image/png;base64,{base64_image}",
"case_sensitive": True
}
response = requests.post(url, headers=headers, json=data)
result = response.json()
print(f"Text: {result['text']}")
print(f"Confidence: {result['confidence']:.2%}")
print(f"Model: {result['model_used']}")
print(f"Processing Time: {result['processing_time']:.3f}s")
Using Fetch API (Browser)
// File Upload Method
const fileInput = document.querySelector('input[type="file"]');
const file = fileInput.files[0];
const formData = new FormData();
formData.append('image', file);
fetch('https://fastcaptcha.org/api/v1/ocr/', {
method: 'POST',
headers: {
'X-API-Key': 'your_api_key_here'
},
body: formData
})
.then(response => response.json())
.then(data => {
console.log('Text:', data.text);
console.log('Confidence:', data.confidence);
console.log('Credits Remaining:', data.credits_remaining);
})
.catch(error => console.error('Error:', error));
// Base64 Method
function imageToBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.onerror = reject;
reader.readAsDataURL(file);
});
}
const base64Image = await imageToBase64(file);
fetch('https://fastcaptcha.org/api/v1/ocr/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-API-Key': 'your_api_key_here'
},
body: JSON.stringify({
base64_image: base64Image,
case_sensitive: true
})
})
.then(response => response.json())
.then(data => {
console.log('Text:', data.text);
console.log('Model Used:', data.model_used);
console.log('Processing Time:', data.processing_time + 's');
});
Using Axios (Install: npm install axios form-data)
const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs');
// File Upload Method
const form = new FormData();
form.append('image', fs.createReadStream('captcha.png'));
axios.post('https://fastcaptcha.org/api/v1/ocr/', form, {
headers: {
...form.getHeaders(),
'X-API-Key': 'your_api_key_here'
}
})
.then(response => {
const data = response.data;
console.log(`Text: ${data.text}`);
console.log(`Confidence: ${data.confidence}`);
console.log(`Credits: ${data.credits_remaining}`);
})
.catch(error => console.error('Error:', error.message));
// Base64 Method
const imageBuffer = fs.readFileSync('captcha.png');
const base64Image = imageBuffer.toString('base64');
axios.post('https://fastcaptcha.org/api/v1/ocr/', {
base64_image: `data:image/png;base64,${base64Image}`,
case_sensitive: true
}, {
headers: {
'Content-Type': 'application/json',
'X-API-Key': 'your_api_key_here'
}
})
.then(response => {
const data = response.data;
console.log(`Text: ${data.text}`);
console.log(`Model: ${data.model_used}`);
console.log(`Time: ${data.processing_time}s`);
});
Using cURL
<?php
// File Upload Method
$url = 'https://fastcaptcha.org/api/v1/ocr/';
$apiKey = 'your_api_key_here';
$imagePath = 'captcha.png';
$ch = curl_init();
$cfile = new CURLFile($imagePath, 'image/png', 'image');
$postData = ['image' => $cfile];
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $postData,
CURLOPT_HTTPHEADER => [
'X-API-Key: ' . $apiKey
],
CURLOPT_RETURNTRANSFER => true
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$result = json_decode($response, true);
echo "Text: " . $result['text'] . "\n";
echo "Confidence: " . $result['confidence'] . "\n";
echo "Credits: " . $result['credits_remaining'] . "\n";
// Base64 Method
$imageData = base64_encode(file_get_contents($imagePath));
$base64Image = 'data:image/png;base64,' . $imageData;
$postData = json_encode([
'base64_image' => $base64Image,
'case_sensitive' => true
]);
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $postData,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'X-API-Key: ' . $apiKey
],
CURLOPT_RETURNTRANSFER => true
]);
$response = curl_exec($ch);
$result = json_decode($response, true);
echo "Text: " . $result['text'] . "\n";
echo "Model: " . $result['model_used'] . "\n";
?>
Using HttpClient (.NET)
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Newtonsoft.Json;
public class FastCaptchaClient
{
private static readonly HttpClient client = new HttpClient();
private const string API_URL = "https://fastcaptcha.org/api/v1/ocr/";
private const string API_KEY = "your_api_key_here";
// File Upload Method
public static async Task<string> SolveCaptchaFile(string imagePath)
{
using (var content = new MultipartFormDataContent())
{
var fileContent = new ByteArrayContent(File.ReadAllBytes(imagePath));
fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("image/png");
content.Add(fileContent, "image", "captcha.png");
client.DefaultRequestHeaders.Add("X-API-Key", API_KEY);
var response = await client.PostAsync(API_URL, content);
var result = await response.Content.ReadAsStringAsync();
dynamic json = JsonConvert.DeserializeObject(result);
Console.WriteLine($"Text: {json.text}");
Console.WriteLine($"Confidence: {json.confidence}");
Console.WriteLine($"Credits: {json.credits_remaining}");
return json.text;
}
}
// Base64 Method
public static async Task<string> SolveCaptchaBase64(string imagePath)
{
byte[] imageBytes = File.ReadAllBytes(imagePath);
string base64Image = $"data:image/png;base64,{Convert.ToBase64String(imageBytes)}";
var payload = new
{
base64_image = base64Image,
case_sensitive = true
};
var json = JsonConvert.SerializeObject(payload);
var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
client.DefaultRequestHeaders.Add("X-API-Key", API_KEY);
var response = await client.PostAsync(API_URL, content);
var result = await response.Content.ReadAsStringAsync();
dynamic data = JsonConvert.DeserializeObject(result);
Console.WriteLine($"Text: {data.text}");
Console.WriteLine($"Model: {data.model_used}");
return data.text;
}
}
Command Line
# File Upload Method
curl -X POST "https://fastcaptcha.org/api/v1/ocr/" \
-H "X-API-Key: your_api_key_here" \
-F "image=@captcha.png"
# Base64 Method
BASE64_IMG=$(base64 -w 0 captcha.png)
curl -X POST "https://fastcaptcha.org/api/v1/ocr/" \
-H "Content-Type: application/json" \
-H "X-API-Key: your_api_key_here" \
-d "{\"base64_image\": \"data:image/png;base64,$BASE64_IMG\", \"case_sensitive\": true}"