How It Works
Our API uses an asynchronous job-based system for reliable scraping:
- Create Job: Send a POST request to create a scraping job
- Get Job ID: Receive a job ID and status check URL
- Poll Status: Check job status every few seconds
- Get Results: When status is "completed", retrieve the scraped data
Why async? Facebook scraping can take 30s to several minutes. Jobs run in the background so your script doesn't timeout or hang.
Quick Start
Follow these 3 simple steps to start scraping Facebook posts:
- Login to your account and generate an API key
- Install Python requests library:
pip install requests - Copy and run the example code below
Step 1: Get Your API Key
- Go to Dashboard → API Keys
- Click "Generate New API Key"
- Give it a name (e.g., "My Scraper")
- Copy the API key (it's only shown once!)
⚠️ Important: Save your API key securely. It won't be shown again!
Step 2: Python Code Example
Minimal Example
import requests
import time
import json
API_KEY = "sk_your_api_key_here"
BASE_URL = "https://scraper-api-e5h6.onrender.com/api/v1"
# Create job
response = requests.post(
f"{BASE_URL}/scraping/api/scrape",
headers={"X-API-Key": API_KEY},
json={
"facebook_url": "https://www.facebook.com/zuck",
"num_posts": 10
}
)
job_id = response.json()["job_id"]
status_url = f"{BASE_URL}/scraping/api/status/{job_id}"
# Poll until complete
while True:
status = requests.get(status_url, headers={"X-API-Key": API_KEY}).json()
print(f"Status: {status['status']}")
if status["status"] == "completed":
print(f"Done! Scraped {status['posts_scraped']} posts")
# Save to file
with open("scraped_data.json", "w", encoding="utf-8") as f:
json.dump(status["result"], f, indent=2, ensure_ascii=False)
print("Data saved to scraped_data.json")
break
elif status["status"] == "failed":
print(f"Failed: {status.get('error', 'Unknown error')}")
break
time.sleep(3)Complete Example
import requests
import json
import time
# Your API key (generated from dashboard)
API_KEY = "sk_your_api_key_here"
BASE_URL = "https://scraper-api-e5h6.onrender.com/api/v1"
# Step 1: Create a scraping job
response = requests.post(
f"{BASE_URL}/scraping/api/scrape",
headers={
"X-API-Key": API_KEY,
"Content-Type": "application/json"
},
json={
"facebook_url": "https://www.facebook.com/zuck",
"num_posts": 10
}
)
if response.status_code != 200:
print(f"Error: {response.json()['detail']}")
exit(1)
# Get job ID
job_data = response.json()
job_id = job_data["job_id"]
print(f"Job created! ID: {job_id}")
print(f"Status: {job_data['status']}")
print(f"Estimated time: {job_data['estimated_time_seconds']}s")
# Step 2: Poll for job status
status_url = f"{BASE_URL}{job_data['status_check_url']}"
print(f"\nChecking status...")
while True:
response = requests.get(status_url, headers={"X-API-Key": API_KEY})
status_data = response.json()
status = status_data["status"]
print(f"Status: {status}")
if status == "completed":
print(f"\nSuccess! Scraped {status_data['posts_scraped']} posts")
# Save the results
with open("scraped_data.json", "w") as f:
json.dump(status_data["result"], f, indent=2)
print(f"Data saved to scraped_data.json")
break
elif status == "failed":
print(f"\nError: {status_data.get('error', 'Unknown error')}")
break
elif status in ["pending", "processing"]:
print(f"Still working... ({status_data.get('posts_scraped', 0)} posts scraped)")
time.sleep(3) # Wait 3 seconds before checking again
else:
print(f"\nUnknown status: {status}")
breakAPI Endpoints
1. Create Scraping Job
POST /api/v1/scraping/api/scrape
Creates a new scraping job and returns job ID
Request Body:
{
"facebook_url": "https://www.facebook.com/zuck",
"num_posts": 10,
"webhook_url": "https://your-server.com/webhook" // Optional
}Response:
{
"job_id": "550e8400-e29b-41d4-a716-446655440000",
"status": "queued",
"message": "Facebook scraping job has been queued for processing",
"estimated_time_seconds": 50,
"status_check_url": "/api/v1/scraping/api/status/550e8400-..."
}2. Check Job Status
GET /api/v1/scraping/api/status/{job_id}
Check the status and get results when complete
Response (Pending/Processing):
{
"job_id": "550e8400-e29b-41d4-a716-446655440000",
"status": "processing",
"posts_scraped": 5,
"created_at": "2025-10-29T12:00:00Z",
"error": null
}Response (Completed):
{
"job_id": "550e8400-e29b-41d4-a716-446655440000",
"status": "completed",
"posts_scraped": 10,
"created_at": "2025-10-29T12:00:00Z",
"completed_at": "2025-10-29T12:01:30Z",
"result": [
{
"post_id": "123456789",
"content": "This is a Facebook post...",
"timestamp": "2025-10-28T10:30:00",
"likes": 150,
"comments": 20,
"shares": 5
}
// ... more posts
]
}Request Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| X-API-Key | Header | ✅ Yes | Your API key from dashboard |
| facebook_url | String | ✅ Yes | Facebook profile/page URL |
| num_posts | Integer | ✅ Yes | Number of posts (1-10) |
| webhook_url | String (URL) | ❌ No | Optional webhook for completion notification |
Job Status Values
pendingJob created, waiting to be processed
processingCurrently scraping Facebook posts
completedScraping finished successfully, results available
failedScraping failed, check error message
cancelledJob was cancelled by user
Common Errors
401 Unauthorized
Invalid or missing API key
402 Payment Required
Insufficient balance or no active subscription
404 Not Found
Job ID not found or doesn't belong to your account
422 Validation Error
Invalid Facebook URL or parameters
500 Server Error
Server issue or internal error
Advanced Example with Full Error Handling
import requests
import json
import time
from datetime import datetime
def scrape_facebook_async(api_key, facebook_url, num_posts,
output_dir="./scraped_data",
poll_interval=3,
timeout=300):
"""
Scrape Facebook posts using async job-based API
Args:
api_key: Your API key
facebook_url: Facebook profile/page URL
num_posts: Number of posts to scrape
output_dir: Directory to save results
poll_interval: Seconds between status checks
timeout: Max seconds to wait for completion
Returns:
dict with success status and data
"""
import os
os.makedirs(output_dir, exist_ok=True)
base_url = "https://scraper-api-e5h6.onrender.com/api/v1"
headers = {
"X-API-Key": api_key,
"Content-Type": "application/json"
}
print(f"Creating scraping job for {facebook_url}...")
print(f"Requesting {num_posts} posts")
# Step 1: Create the job
try:
response = requests.post(
f"{base_url}/scraping/api/scrape",
headers=headers,
json={
"facebook_url": facebook_url,
"num_posts": num_posts
}
)
if response.status_code != 200:
error = response.json().get('detail', 'Unknown error')
print(f"Error creating job: {error}")
return {"success": False, "error": error}
job_data = response.json()
job_id = job_data["job_id"]
status_url = f"{base_url}{job_data['status_check_url']}"
print(f"\n✓ Job created successfully")
print(f" Job ID: {job_id}")
print(f" Status: {job_data['status']}")
print(f" Estimated time: {job_data['estimated_time_seconds']}s")
except Exception as e:
print(f"Error: {e}")
return {"success": False, "error": str(e)}
# Step 2: Poll for completion
print(f"\nMonitoring job progress...")
start_time = time.time()
while True:
elapsed = time.time() - start_time
# Check timeout
if elapsed > timeout:
print(f"\n⚠ Timeout after {timeout}s")
return {"success": False, "error": "Timeout"}
# Check status
try:
response = requests.get(status_url, headers=headers)
status_data = response.json()
status = status_data["status"]
posts_scraped = status_data.get("posts_scraped", 0)
# Update progress
if status == "processing":
print(f" [{elapsed:.0f}s] Processing... {posts_scraped} posts scraped")
elif status == "pending":
print(f" [{elapsed:.0f}s] Waiting in queue...")
elif status == "completed":
# Success! Save the data
print(f"\n✓ Scraping completed!")
print(f" Posts scraped: {posts_scraped}")
print(f" Duration: {elapsed:.1f}s")
filename = f"facebook_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
filepath = os.path.join(output_dir, filename)
with open(filepath, "w", encoding="utf-8") as f:
json.dump(status_data["result"], f, indent=2, ensure_ascii=False)
print(f" File saved: {filepath}")
return {
"success": True,
"filepath": filepath,
"posts_scraped": posts_scraped,
"duration": elapsed
}
elif status == "failed":
error = status_data.get("error", "Unknown error")
print(f"\n✗ Scraping failed: {error}")
return {"success": False, "error": error}
# Wait before next check
time.sleep(poll_interval)
except Exception as e:
print(f"\nError checking status: {e}")
return {"success": False, "error": str(e)}
# Usage example
if __name__ == "__main__":
result = scrape_facebook_async(
api_key="sk_your_api_key_here",
facebook_url="https://www.facebook.com/zuck",
num_posts=10,
poll_interval=3,
timeout=300
)
if result["success"]:
print(f"\nSuccess! Data saved to {result['filepath']}")
else:
print(f"\nFailed: {result['error']}")Tips & Best Practices
- ✓Store your API key in environment variables, not in code
- ✓Poll status every 3-5 seconds to avoid overwhelming the server
- ✓Set a reasonable timeout (5-10 minutes) for large scraping jobs
- ✓Start with small number of posts (10-20) to test
- ✓Check your balance before making large requests
- ✓Handle all job statuses (pending, processing, completed, failed)
- ✗Never commit API keys to version control
- ✗Don't poll too frequently (less than 1 second intervals)
- ✗Don't share API keys publicly or in screenshots