API Docs

How It Works

Our API uses an asynchronous job-based system for reliable scraping:

  1. Create Job: Send a POST request to create a scraping job
  2. Get Job ID: Receive a job ID and status check URL
  3. Poll Status: Check job status every few seconds
  4. 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:

  1. Login to your account and generate an API key
  2. Install Python requests library: pip install requests
  3. Copy and run the example code below

Step 1: Get Your API Key

  1. Go to Dashboard → API Keys
  2. Click "Generate New API Key"
  3. Give it a name (e.g., "My Scraper")
  4. 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}")
        break

API 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,
      "shared_post": null,  // the original post when this one is a share (see the kinds reference)
      "videos": []  // playable videos: {id, hd_url, sd_url, thumbnail_url, duration_sec, width, height}
    }
    // ... more posts
  ]
}

Job Kinds

Every job kind has its own endpoint. Send {"params": {...}, "max_items": N} with your X-API-Key header. max_items must be between 1 and the kind's API cap (a higher value is a 422). The response (201) is the job, with its id.

Poll GET /api/v1/scraping/jobs/{id} for status and GET /api/v1/scraping/jobs/{id}/items?after_seq=0 for results; items arrive while the job runs, up to 500 per page. Pass the last seq you saw as after_seq. Errors: 402 not enough credits, 422 bad params, 429 busy (wait for Retry-After seconds). An Idempotency-Key header makes a retried POST return the same job.

The full list of kinds is also served as JSON at GET /api/v1/scraping/kinds.

Posts & profiles

Profile / Page posts profile_posts

POST /api/v1/scraping/kinds/profile_posts

Latest posts from a public Page or profile.

  • Item: 1 item = 1 post. Credits are charged per item delivered.
  • Max items per job: API 1,200 · dashboard 300
  • Params: url or profile_id
ParamTypeNotes
urlstringone of the alternatives
profile_idstringone of the alternatives · Numeric profile or Page ID
curl -X POST "https://scraper-api-e5h6.onrender.com/api/v1/scraping/kinds/profile_posts" \
  -H "X-API-Key: sk_your_api_key_here" \
  -H "Content-Type: application/json" \
  -d '{"params":{"url":"https://www.facebook.com/bdnews24"},"max_items":10}'
Shared posts: shared_post

When a post is a share, the item's own fields (content, reactions, comments) are the sharer's, and shared_post holds the original post. It is null when the post is not a share. Attachments use the same shape as the top-level attachments. The original's counts are null when Facebook does not send them. If the original was deleted or made private, shared_post is {"unavailable": true, "unavailable_reason": "..."} with the other fields null or empty.

"shared_post": {
  "post_id": "1610987997726350",
  "url": "https://www.facebook.com/thetelegraphindia/posts/pfbid0...",
  "author": { "name": "The Telegraph", "id": "100064541066318", "url": "https://www.facebook.com/thetelegraphindia" },
  "text": "State Repression of Free Media: A Dark Chapter...",
  "created_time": "2026-11-17T12:34:18Z",
  "media_urls": ["https://scontent.xx.fbcdn.net/..."],
  "attachments": [{ "type": "Photo", "url": "https://scontent.xx.fbcdn.net/..." }],
  "likes": null, "num_comments": null, "num_shares": null,
  "videos": [],
  "unavailable": false
}
Videos: videos

videos lists the post's playable videos, in attachment order ([] when it has none). hd_url and sd_url are direct MP4 files; either can be null. The best one (HD, else SD) is also appended to media_urls, after the images. A shared post's original carries its own shared_post.videos. The URLs are signed by Facebook and expire, so download them soon after the job finishes. CSV exports add a video_urls column (space separated).

"media_urls": ["https://video.xx.fbcdn.net/o1/v/t2/f2/m366/...mp4?..."],
"videos": [
  {
    "id": "1770872960683267",
    "hd_url": "https://video.xx.fbcdn.net/o1/v/t2/f2/m366/...mp4?...",
    "sd_url": "https://video.xx.fbcdn.net/o1/v/t2/f2/m412/...mp4?...",
    "thumbnail_url": "https://scontent.xx.fbcdn.net/v/t15.5256-10/...jpg",
    "duration_sec": 18.992,
    "width": 720,
    "height": 1280
  }
]

Single post post

POST /api/v1/scraping/kinds/post

One post by its link: text, reactions, media.

  • Item: 1 item = 1 post. Credits are charged per item delivered.
  • Max items per job: single result (max_items not needed)
ParamTypeNotes
urlstringrequired
curl -X POST "https://scraper-api-e5h6.onrender.com/api/v1/scraping/kinds/post" \
  -H "X-API-Key: sk_your_api_key_here" \
  -H "Content-Type: application/json" \
  -d '{"params":{"url":"https://www.facebook.com/bdnews24/posts/pfbid0…"}}'
Shared posts: shared_post

When a post is a share, the item's own fields (content, reactions, comments) are the sharer's, and shared_post holds the original post. It is null when the post is not a share. Attachments use the same shape as the top-level attachments. The original's counts are null when Facebook does not send them. If the original was deleted or made private, shared_post is {"unavailable": true, "unavailable_reason": "..."} with the other fields null or empty.

"shared_post": {
  "post_id": "1610987997726350",
  "url": "https://www.facebook.com/thetelegraphindia/posts/pfbid0...",
  "author": { "name": "The Telegraph", "id": "100064541066318", "url": "https://www.facebook.com/thetelegraphindia" },
  "text": "State Repression of Free Media: A Dark Chapter...",
  "created_time": "2026-11-17T12:34:18Z",
  "media_urls": ["https://scontent.xx.fbcdn.net/..."],
  "attachments": [{ "type": "Photo", "url": "https://scontent.xx.fbcdn.net/..." }],
  "likes": null, "num_comments": null, "num_shares": null,
  "videos": [],
  "unavailable": false
}
Videos: videos

videos lists the post's playable videos, in attachment order ([] when it has none). hd_url and sd_url are direct MP4 files; either can be null. The best one (HD, else SD) is also appended to media_urls, after the images. A shared post's original carries its own shared_post.videos. The URLs are signed by Facebook and expire, so download them soon after the job finishes. CSV exports add a video_urls column (space separated).

"media_urls": ["https://video.xx.fbcdn.net/o1/v/t2/f2/m366/...mp4?..."],
"videos": [
  {
    "id": "1770872960683267",
    "hd_url": "https://video.xx.fbcdn.net/o1/v/t2/f2/m366/...mp4?...",
    "sd_url": "https://video.xx.fbcdn.net/o1/v/t2/f2/m412/...mp4?...",
    "thumbnail_url": "https://scontent.xx.fbcdn.net/v/t15.5256-10/...jpg",
    "duration_sec": 18.992,
    "width": 720,
    "height": 1280
  }
]

Page info page_info

POST /api/v1/scraping/kinds/page_info

A Page's about details: category, contact, followers.

  • Item: 1 item = 1 page. Credits are charged per item delivered.
  • Max items per job: single result (max_items not needed)
ParamTypeNotes
urlstringrequired
curl -X POST "https://scraper-api-e5h6.onrender.com/api/v1/scraping/kinds/page_info" \
  -H "X-API-Key: sk_your_api_key_here" \
  -H "Content-Type: application/json" \
  -d '{"params":{"url":"https://www.facebook.com/bdnews24"}}'

Comments

Post comments post_comments

POST /api/v1/scraping/kinds/post_comments

Top-level comments on a public post.

  • Item: 1 item = 1 comment. Credits are charged per item delivered.
  • Max items per job: API 3,000 · dashboard 500
  • Params: url or feedback_id; top-level comments only
ParamTypeNotes
urlstringone of the alternatives
feedback_idstringone of the alternatives · The post's feedback id (from the API)
sortenumoptional · relevant, all · default relevant
curl -X POST "https://scraper-api-e5h6.onrender.com/api/v1/scraping/kinds/post_comments" \
  -H "X-API-Key: sk_your_api_key_here" \
  -H "Content-Type: application/json" \
  -d '{"params":{"url":"https://www.facebook.com/bdnews24/posts/pfbid0…"},"max_items":10}'

Media

Reels profile_reels

POST /api/v1/scraping/kinds/profile_reels

Reels from a Page or profile, with views and length.

  • Item: 1 item = 1 reel. Credits are charged per item delivered.
  • Max items per job: API 500 · dashboard 100
ParamTypeNotes
urlstringrequired
curl -X POST "https://scraper-api-e5h6.onrender.com/api/v1/scraping/kinds/profile_reels" \
  -H "X-API-Key: sk_your_api_key_here" \
  -H "Content-Type: application/json" \
  -d '{"params":{"url":"https://www.facebook.com/bdnews24"},"max_items":10}'

Photos profile_photos

POST /api/v1/scraping/kinds/profile_photos

Photos from a Page or profile's photo tab.

  • Item: 1 item = 1 photo. Credits are charged per item delivered.
  • Max items per job: API 2,000 · dashboard 400
ParamTypeNotes
urlstringrequired
curl -X POST "https://scraper-api-e5h6.onrender.com/api/v1/scraping/kinds/profile_photos" \
  -H "X-API-Key: sk_your_api_key_here" \
  -H "Content-Type: application/json" \
  -d '{"params":{"url":"https://www.facebook.com/bdnews24"},"max_items":10}'

Events

Page events page_events

POST /api/v1/scraping/kinds/page_events

Events hosted by a Page.

  • Item: 1 item = 1 event. Credits are charged per item delivered.
  • Max items per job: API 1,000 · dashboard 200
ParamTypeNotes
urlstringrequired
curl -X POST "https://scraper-api-e5h6.onrender.com/api/v1/scraping/kinds/page_events" \
  -H "X-API-Key: sk_your_api_key_here" \
  -H "Content-Type: application/json" \
  -d '{"params":{"url":"https://www.facebook.com/metmuseum"},"max_items":10}'

Single event event

POST /api/v1/scraping/kinds/event

One event: date, place, description, responses.

  • Item: 1 item = 1 event. Credits are charged per item delivered.
  • Max items per job: single result (max_items not needed)
  • Params: url or event_id
ParamTypeNotes
urlstringone of the alternatives
event_idstringone of the alternatives
curl -X POST "https://scraper-api-e5h6.onrender.com/api/v1/scraping/kinds/event" \
  -H "X-API-Key: sk_your_api_key_here" \
  -H "Content-Type: application/json" \
  -d '{"params":{"url":"https://www.facebook.com/events/1333058394763810/"}}'

City events city_events

POST /api/v1/scraping/kinds/city_events

Upcoming events in a city.

  • Item: 1 item = 1 event. Credits are charged per item delivered.
  • Max items per job: API 1,000 · dashboard 200
  • Params: city_id, explore_url or city_slug
ParamTypeNotes
city_slugstringone of the alternatives · City slug as in facebook.com/marketplace/<city>/
city_idstringone of the alternatives
explore_urlstringone of the alternatives
curl -X POST "https://scraper-api-e5h6.onrender.com/api/v1/scraping/kinds/city_events" \
  -H "X-API-Key: sk_your_api_key_here" \
  -H "Content-Type: application/json" \
  -d '{"params":{"city_slug":"dhaka"},"max_items":10}'

Groups

Group info group_info

POST /api/v1/scraping/kinds/group_info

A public group: members, privacy, activity.

  • Item: 1 item = 1 group. Credits are charged per item delivered.
  • Max items per job: single result (max_items not needed)
  • Params: url or group_id
ParamTypeNotes
urlstringone of the alternatives
group_idstringone of the alternatives
curl -X POST "https://scraper-api-e5h6.onrender.com/api/v1/scraping/kinds/group_info" \
  -H "X-API-Key: sk_your_api_key_here" \
  -H "Content-Type: application/json" \
  -d '{"params":{"url":"https://www.facebook.com/groups/…"}}'

Group posts group_posts

POST /api/v1/scraping/kinds/group_posts

Latest posts in a public group.

  • Item: 1 item = 1 post. Credits are charged per item delivered.
  • Max items per job: API 1,200 · dashboard 300
  • Params: url or group_id
ParamTypeNotes
urlstringone of the alternatives
group_idstringone of the alternatives
curl -X POST "https://scraper-api-e5h6.onrender.com/api/v1/scraping/kinds/group_posts" \
  -H "X-API-Key: sk_your_api_key_here" \
  -H "Content-Type: application/json" \
  -d '{"params":{"url":"https://www.facebook.com/groups/…"},"max_items":10}'
Shared posts: shared_post

When a post is a share, the item's own fields (content, reactions, comments) are the sharer's, and shared_post holds the original post. It is null when the post is not a share. Attachments use the same shape as the top-level attachments. The original's counts are null when Facebook does not send them. If the original was deleted or made private, shared_post is {"unavailable": true, "unavailable_reason": "..."} with the other fields null or empty.

"shared_post": {
  "post_id": "1610987997726350",
  "url": "https://www.facebook.com/thetelegraphindia/posts/pfbid0...",
  "author": { "name": "The Telegraph", "id": "100064541066318", "url": "https://www.facebook.com/thetelegraphindia" },
  "text": "State Repression of Free Media: A Dark Chapter...",
  "created_time": "2026-11-17T12:34:18Z",
  "media_urls": ["https://scontent.xx.fbcdn.net/..."],
  "attachments": [{ "type": "Photo", "url": "https://scontent.xx.fbcdn.net/..." }],
  "likes": null, "num_comments": null, "num_shares": null,
  "videos": [],
  "unavailable": false
}
Videos: videos

videos lists the post's playable videos, in attachment order ([] when it has none). hd_url and sd_url are direct MP4 files; either can be null. The best one (HD, else SD) is also appended to media_urls, after the images. A shared post's original carries its own shared_post.videos. The URLs are signed by Facebook and expire, so download them soon after the job finishes. CSV exports add a video_urls column (space separated).

"media_urls": ["https://video.xx.fbcdn.net/o1/v/t2/f2/m366/...mp4?..."],
"videos": [
  {
    "id": "1770872960683267",
    "hd_url": "https://video.xx.fbcdn.net/o1/v/t2/f2/m366/...mp4?...",
    "sd_url": "https://video.xx.fbcdn.net/o1/v/t2/f2/m412/...mp4?...",
    "thumbnail_url": "https://scontent.xx.fbcdn.net/v/t15.5256-10/...jpg",
    "duration_sec": 18.992,
    "width": 720,
    "height": 1280
  }
]

Marketplace

Marketplace item marketplace_item

POST /api/v1/scraping/kinds/marketplace_item

One listing: price, photos, description, seller.

  • Item: 1 item = 1 listing. Credits are charged per item delivered.
  • Max items per job: single result (max_items not needed)
  • Params: url or item_id
ParamTypeNotes
urlstringone of the alternatives
item_idstringone of the alternatives
curl -X POST "https://scraper-api-e5h6.onrender.com/api/v1/scraping/kinds/marketplace_item" \
  -H "X-API-Key: sk_your_api_key_here" \
  -H "Content-Type: application/json" \
  -d '{"params":{"url":"https://www.facebook.com/marketplace/item/…"}}'

Ad Library

Company ads company_ads

POST /api/v1/scraping/kinds/company_ads

All ads of one advertiser, by Page ID.

  • Item: 1 item = 1 ad. Credits are charged per item delivered.
  • Max items per job: API 2,000 · dashboard 300
  • Params: page_id from company_search
ParamTypeNotes
countrystringoptional · default ALL · ALL or a two-letter code, e.g. BD
active_statusenumoptional · active, inactive, all · default all
media_typeenumoptional · all · default all
page_idstringrequired · From a Company search result
curl -X POST "https://scraper-api-e5h6.onrender.com/api/v1/scraping/kinds/company_ads" \
  -H "X-API-Key: sk_your_api_key_here" \
  -H "Content-Type: application/json" \
  -d '{"params":{"page_id":"1234567890"},"max_items":10}'

Ad details ad_details

POST /api/v1/scraping/kinds/ad_details

One ad by its Ad Library ID.

  • Item: 1 item = 1 ad. Credits are charged per item delivered.
  • Max items per job: single result (max_items not needed)
ParamTypeNotes
ad_archive_idstringrequired
page_idstringoptional · From a Company search result
countrystringoptional · default ALL · ALL or a two-letter code, e.g. BD
curl -X POST "https://scraper-api-e5h6.onrender.com/api/v1/scraping/kinds/ad_details" \
  -H "X-API-Key: sk_your_api_key_here" \
  -H "Content-Type: application/json" \
  -d '{"params":{"ad_archive_id":"1234567890"}}'

Discovery

Answers topic answers

POST /api/v1/scraping/kinds/answers

A Facebook Answers topic page with all its sections.

  • Item: 1 item = 1 topic page. Credits are charged per item delivered.
  • Max items per job: single result (max_items not needed)
  • Params: slug or url
ParamTypeNotes
slugstringone of the alternatives
urlstringone of the alternatives
curl -X POST "https://scraper-api-e5h6.onrender.com/api/v1/scraping/kinds/answers" \
  -H "X-API-Key: sk_your_api_key_here" \
  -H "Content-Type: application/json" \
  -d '{"params":{"slug":"best-biryani-in-dhaka"}}'

Why a job failed

A failed job's error_message holds one of these codes (a temporary failure reads transient: <code>). You are charged only for items delivered; a job that failed before delivering anything costs 0 credits.

codemeaning
invalid_urlThat link isn't a Facebook page this job can read. Check the URL.
invalid_queryThe search words are empty or too long.
invalid_locationGive a city, or both latitude and longitude.
invalid_paramsSome options are not supported. Check the form values.
invalid_filtersSome filters are not supported. Check the form values.
invalid_page_idThe Page ID must be a number (find it with Company search).
invalid_ad_idThe Ad Library ID must be a number.
invalid_slugThat topic slug isn't valid.
invalid_cityThat city isn't valid.
unknown_city_slugFacebook doesn't know that city name. Try the name as it appears in facebook.com/marketplace/<city>/.
no_city_pageFacebook has no events page for that city.
tab_not_foundThat Page has no such tab (no reels, photos or events to list).
content_unavailableFacebook says this content isn't available. It may be private, deleted or age-restricted.
node_nullFacebook returned nothing for this target. It may be private or need a login.
geoblockedThis content isn't available from our region.
ad_not_foundNo ad with that ID was found in the Ad Library.
offsite_redirectThe link redirected away from Facebook, so it was not followed.
unresolved_idWe couldn't find that profile or Page.
hiddenThis profile hides its posts from logged-out visitors.
hidden_cachedThis profile hides its posts from logged-out visitors.
login_wallFacebook asked for a login to show this.
runaway_guardStopped: Facebook kept returning pages without new results.
rate_limitedFacebook is limiting requests right now. Try again later.
egress_downOur scraping network was unavailable. Try again later.
bad_cursorFacebook rejected the next page request. Try again later.
bad_variablesFacebook rejected the request. Try again later.
unauthorizedFacebook does not allow this request without a login.
truncatedFacebook sent an incomplete page. Try again later.
op_errorFacebook returned an error. Try again later.
js_challengeFacebook asked for a browser check. Try again later.

Request Parameters

ParameterTypeRequiredDescription
X-API-KeyHeader✅ YesYour API key from dashboard
facebook_urlString✅ YesFacebook profile/page URL
num_postsInteger✅ YesNumber of posts (1-10)
webhook_urlString (URL)❌ NoOptional 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

Billing

  • • 1 credit per post delivered. You are charged only for the posts a job delivers. Failed jobs cost nothing.
  • • When credits are short, creating a job returns HTTP 402 with the detail Not enough credits: need N, available M.
  • • Buy credits with bKash on the Buy credits page. Credits never expire.

Common Errors

401 Unauthorized

Invalid or missing API key

402 Payment Required

Not enough credits. The detail reads Not enough credits: need N, available M

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 credits 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