/scraperapi:scraperapi-php-sdkfrom ScraperAPI
Best-practices reference for the ScraperAPI PHP SDK. Covers Composer setup, request parameters, escalation ladder, POST requests, error handling, and credit costs.
Ships in ScraperAPI. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Requires: PHP 7.0+, Composer, composer require scraperapi/sdk, a ScraperAPI API key.
<?php
require __DIR__ . '/vendor/autoload.php';
use ScraperAPI\Client;
$client = new Client('YOUR_API_KEY');
Replace YOUR_API_KEY with your key from https://dashboard.scraperapi.com. Never commit a real key to source control.
// Simple GET — returns HTML string via ->raw_body
$html = $client->get("https://example.com/")->raw_body;
echo $html;
// With a single parameter
$html = $client->get("https://example.com/", ["render" => true])->raw_body;
// With multiple parameters
$html = $client->get(
"https://example.com/",
[
"render" => true,
"country_code" => "us",
]
)->raw_body;
Parameters are passed as an associative array. ->raw_body extracts the HTML string from the response object.
| Situation | Approach |
|---|---|
| Single URL, synchronous | $client->get($url, $params)->raw_body |
| Page loads content via JavaScript | Add "render" => true |
| Site blocks datacenter proxies | Add "premium" => true |
| Toughest anti-bot protection | Add "ultra_premium" => true |
| Multi-step / paginated flow on same domain | Use "session_number" |
| POST a form or JSON body to target | $client->post($url, $options)->raw_body |
| 20+ URLs or batch jobs | Use async endpoint via cURL or Guzzle |
| Supported platform (Amazon, Google, etc.) | Use structured data endpoint directly |
// Render JavaScript before returning HTML
// Use when: page is a React/Vue/Angular SPA, or scrape returns empty/partial content
// Cost: 10 credits per request (instead of 1)
$html = $client->get("https://spa-site.com/", ["render" => true])->raw_body;
// Wait for a specific DOM element (requires render: true)
$html = $client->get("https://spa-site.com/", [
"render" => true,
"wait_for_selector" => ".product-list",
])->raw_body;
// Screenshot (auto-enables rendering)
$html = $client->get("https://example.com/", ["screenshot" => true])->raw_body;
Start without render. Add it only when the response is missing expected content — it increases cost and latency.
// Route through a country-specific proxy — no extra credit cost
$html = $client->get("https://example.com/", ["country_code" => "de"])->raw_body;
// Premium residential/mobile IPs — for sites that block datacenter proxies
// Cost: 10 credits (25 with render)
$html = $client->get("https://hard-site.com/", ["premium" => true])->raw_body;
// Ultra-premium — for the toughest anti-bot protections
// Cost: 30 credits (75 with render)
// Note: incompatible with custom headers — keep_headers is ignored
$html = $client->get("https://hardest-site.com/", ["ultra_premium" => true])->raw_body;
premium and ultra_premium are mutually exclusive — never set both.
Escalation order: standard (1 cr) → render (10 cr) → premium (10 cr) → ultra_premium (30 cr).
// Reuse the same proxy IP across requests — useful for pagination and multi-step flows
// Sessions expire 15 minutes after last use; any integer is a valid session ID
$html1 = $client->get("https://example.com/page1", ["session_number" => 42])->raw_body;
$html2 = $client->get("https://example.com/page2", ["session_number" => 42])->raw_body;
// Forward custom headers to the target site
// Note: keep_headers is ignored when ultra_premium is true
$html = $client->get("https://example.com/", [
"keep_headers" => true,
])->raw_body;
// Pass headers in the request options array alongside ScraperAPI params
// Emulate a mobile or desktop browser user-agent
$html = $client->get("https://example.com/", ["device_type" => "mobile"])->raw_body;
// Return structured JSON instead of HTML for supported sites (Amazon, Google, etc.)
$json = $client->get("https://amazon.com/dp/B09V3KXJPB", ["autoparse" => true])->raw_body;
$data = json_decode($json, true);
// Markdown output — useful for text pipelines
$md = $client->get("https://docs.example.com/", ["output_format" => "markdown"])->raw_body;
// POST a JSON body to the target site through ScraperAPI's proxy
$options = [
"body" => json_encode(["key" => "value"]),
"headers" => ["Content-Type" => "application/json"],
];
$result = $client->post("https://example.com/api", $options)->raw_body;
Always start with the cheapest option and escalate only when blocked.
function scrapeWithEscalation(Client $client, string $url): ?string
{
$tiers = [
[],
["render" => true],
["premium" => true],
["premium" => true, "render" => true],
["ultra_premium" => true],
];
foreach ($tiers as $params) {
$html = $client->get($url, $params)->raw_body;
if ($html && stripos($html, '<html') !== false) {
return $html;
}
}
return null;
}
The SDK is synchronous — each ->get() call blocks until the response (up to 70 seconds). For 20+ URLs, use the async REST endpoint.
const API_KEY = 'YOUR_API_KEY';
function submitJob(string $url, array $apiParams = []): array
{
$context = stream_context_create(['http' => [
'method' => 'POST',
'header' => 'Content-Type: application/json',
'content' => json_encode(['apiKey' => API_KEY, 'url' => $url, 'apiParams' => $apiParams]),
]]);
$response = file_get_contents('https://async.scraperapi.com/jobs', false, $context);
return json_decode($response, true); // ["id" => "...", "statusUrl" => "..."]
}
function pollJob(array $job, int $maxWait = 120, int $interval = 5): string
{
$deadline = time() + $maxWait;
while (time() < $deadline) {
$data = json_decode(file_get_contents($job['statusUrl']), true);
if ($data['status'] === 'finished') return $data['response']['body'];
if ($data['status'] === 'failed') throw new \RuntimeException("Job {$job['id']} failed");
sleep($interval);
}
throw new \RuntimeException("Job {$job['id']} timed out");
}
// Submit and collect
$urls = ['https://example.com/p1', 'https://example.com/p2'];
$jobs = array_map('submitJob', $urls);
$results = array_map('pollJob', $jobs);
For supported platforms, use structured endpoints instead of raw HTML — they return clean JSON without parsing logic.
function structuredGet(string $vertical, array $params = []): array
{
$query = http_build_query(array_merge(['api_key' => API_KEY], $params));
$url = "https://api.scraperapi.com/structured/{$vertical}?{$query}";
$body = file_get_contents($url);
if ($body === false) throw new \RuntimeException("Request failed for {$vertical}");
return json_decode($body, true);
}
// Google SERP
$results = structuredGet('google/search', ['query' => 'PHP web scraping']);
// Amazon product details
$product = structuredGet('amazon/product', ['asin' => 'B09V3KXJPB']);
// Walmart search
$items = structuredGet('walmart/search', ['query' => 'standing desk', 'tld' => 'com']);
See structured data docs for all verticals and required fields.
function safeScrape(Client $client, string $url, array $params = []): ?string
{
try {
return $client->get($url, $params)->raw_body;
} catch (\Exception $e) {
$status = method_exists($e, 'getCode') ? (int) $e->getCode() : 0;
switch ($status) {
case 401: throw new \RuntimeException('Invalid API key — check your API key');
case 403: throw new \RuntimeException("Out of API credits for this billing cycle — upgrade or enable overages at https://dashboard.scraperapi.com/billing (don't retry)");
case 429: throw new \RuntimeException('Rate limit — reduce concurrency or switch to async');
case 500:
case 503: throw new \RuntimeException('Failed after ScraperAPI retried for 70s (not charged) — retry; on protected sites add premium');
default: throw $e;
}
}
}
Status code reference: 200 success, 401 bad key, 403 credits exhausted (don't retry), 404 target not found (charged), 429 concurrency limit, 500 failed after 70s of retries (not charged — retry, then escalate to premium/ultra_premium on protected sites).
Also see retry docs.
| Request type | Credits |
|---|---|
| Standard | 1 |
"render" => true | 10 |
"premium" => true | 10 |
"premium" => true, "render" => true | 25 |
"ultra_premium" => true | 30 |
"ultra_premium" => true, "render" => true | 75 |
Those are the costs on a normal site. Some sites cost more per request, before any parameters:
| Site | Credits |
|---|---|
| Amazon, Walmart, eBay | 5 |
| Google, Bing (all subdomains) | 25 |
| 30 | |
| Sites behind Cloudflare, DataDome, PerimeterX or Akamai | 10 |
You're charged for 200 and 404 responses, and for requests you cancel before ScraperAPI's 70s
of retries finish. Each response's sa-credit-cost header shows what it cost; preview a cost
without spending credits with GET https://api.scraperapi.com/account/urlcost?api_key=...&url=...
(it accepts the same parameters). Source: https://docs.scraperapi.com/getting-started/quick-start/credits-and-requests-costs
Add "max_cost" => N to any request to cap credit spend — returns 403 if the request would cost more than N credits.
What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub scraperapi/scraperapi-skills --plugin scraperapi20 skills in this plugin
/scraperapi-agent-onboardingEntry point for agents and developers new to ScraperAPI. Read first when integrating ScraperAPI into an agent or app, setting up the MCP server for Claude Code or other LLM tools, choosing the right ScraperAPI product, or getting an API key. Trigger on: "how do I use ScraperAPI", "set up ScraperAPI", "connect ScraperAPI to Claude", "which ScraperAPI product should I use", "get web data for my agent", "add web scraping to my project", "ScraperAPI getting started". After reading, route to the narrower skill that owns the chosen path. If the user already named a language or SDK, n8n, Zapier, or the sapi CLI, use that skill directly instead.
Note: Transmits user-supplied queries, URLs, and content to ScraperAPI.
/scraperapi-asyncReference for ScraperAPI's Async Jobs REST API: submit scraping jobs in the background and get results by polling or webhook, including batch jobs. Consult when the user is scraping many URLs, needs non-blocking requests, or wants webhook delivery. Use when user asks: "how do I scrape 1000 URLs with ScraperAPI", "ScraperAPI async jobs", "batch scraping with ScraperAPI", "submit a scraping job and poll for results", "ScraperAPI webhook callback", "ScraperAPI batchjobs endpoint". Covers single and batch jobs, webhook callbacks, apiParams, async-only parameters, binary responses, retention, and error handling. It is language-agnostic: for SDK client code, use the language's SDK skill; to crawl a whole site by following links, use scraperapi-crawler.
Note: Transmits user-supplied queries, URLs, and content to ScraperAPI.
Other plugins' skills for the same job