> For the complete documentation index, see [llms.txt](https://docs.iproyal.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.iproyal.com/scraping-tools/web-scraper-api-beta/api/usage.md).

# Usage

Returns usage totals for a date range or for all time.

```
GET /v1/usage
```

### Query Parameters

| Parameter   | Type   | Required | Description                           |
| ----------- | ------ | -------- | ------------------------------------- |
| `date_from` | string | No       | First day to include, as `YYYY-MM-DD` |
| `date_to`   | string | No       | Last day to include, as `YYYY-MM-DD`  |

* Both days are included in the range.
* Days are calendar days in UTC.
* Omit both parameters to get totals for all time.
* Send only one for an open range. For example, `date_from` alone counts from that day onward.

{% tabs %}
{% tab title="cURL" %}

```bash
curl "https://scrape.iproyal.com/v1/usage?date_from=2026-09-01&date_to=2026-09-30" \
  -H "Authorization: Bearer $WEB_SCRAPER_API_TOKEN"
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php

$query = http_build_query(['date_from' => '2026-09-01', 'date_to' => '2026-09-30']);
$ch = curl_init('https://scrape.iproyal.com/v1/usage?' . $query);

curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . getenv('WEB_SCRAPER_API_TOKEN'),
    ],
]);

$usage = json_decode(curl_exec($ch), true);
$successRate = $usage['total'] > 0 ? $usage['successful'] / $usage['total'] : 0;

printf("%d requests, %.1f%% successful, %d credits used\n", $usage['total'], $successRate * 100, $usage['credits']);
```

{% endtab %}

{% tab title="Python" %}

```python
import os

import requests

response = requests.get(
    "https://scrape.iproyal.com/v1/usage",
    headers={"Authorization": f"Bearer {os.environ['WEB_SCRAPER_API_TOKEN']}"},
    params={"date_from": "2026-09-01", "date_to": "2026-09-30"},
    timeout=30,
)
response.raise_for_status()

usage = response.json()
success_rate = usage["successful"] / usage["total"] if usage["total"] else 0
print(f"{usage['total']} requests, {success_rate:.1%} successful, {usage['credits']} credits used")
```

{% endtab %}

{% tab title="Node.js" %}

```javascript
const params = new URLSearchParams({ date_from: '2026-09-01', date_to: '2026-09-30' });

const response = await fetch(`https://scrape.iproyal.com/v1/usage?${params}`, {
  headers: { Authorization: `Bearer ${process.env.WEB_SCRAPER_API_TOKEN}` },
  signal: AbortSignal.timeout(30_000),
});

const usage = await response.json();
const successRate = usage.total ? usage.successful / usage.total : 0;
console.log(`${usage.total} requests, ${(successRate * 100).toFixed(1)}% successful, ${usage.credits} credits used`);
```

{% endtab %}

{% tab title="Java" %}

```java
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;

public class UsageExample {
    public static void main(String[] args) throws Exception {
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://scrape.iproyal.com/v1/usage?date_from=2026-09-01&date_to=2026-09-30"))
            .header("Authorization", "Bearer " + System.getenv("WEB_SCRAPER_API_TOKEN"))
            .timeout(Duration.ofSeconds(30))
            .GET()
            .build();

        HttpResponse<String> response = HttpClient.newHttpClient()
            .send(request, HttpResponse.BodyHandlers.ofString());
        JsonNode usage = new ObjectMapper().readTree(response.body());

        long total = usage.get("total").asLong();
        double successRate = total > 0 ? (double) usage.get("successful").asLong() / total : 0;
        System.out.printf("%d requests, %.1f%% successful, %d credits used%n", total, successRate * 100, usage.get("credits").asLong());
    }
}
```

{% endtab %}

{% tab title="Go" %}

```go
package main

import (
	"encoding/json"
	"fmt"
	"net/http"
	"net/url"
	"os"
	"time"
)

type usage struct {
	DateFrom      *string        `json:"date_from"`
	DateTo        *string        `json:"date_to"`
	Total         int64          `json:"total"`
	Successful    int64          `json:"successful"`
	Failed        int64          `json:"failed"`
	Credits       int64          `json:"credits"`
	Latency       int64          `json:"latency"`
	ByRequestType map[string]int `json:"by_request_type"`
	ByStatus      map[string]int `json:"by_status"`
}

func main() {
	query := url.Values{"date_from": {"2026-09-01"}, "date_to": {"2026-09-30"}}

	req, _ := http.NewRequest(http.MethodGet, "https://scrape.iproyal.com/v1/usage?"+query.Encode(), nil)
	req.Header.Set("Authorization", "Bearer "+os.Getenv("WEB_SCRAPER_API_TOKEN"))

	client := &http.Client{Timeout: 30 * time.Second}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("request failed:", err)
		return
	}
	defer resp.Body.Close()

	var body usage
	if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
		fmt.Println("unexpected response:", err)
		return
	}

	successRate := 0.0
	if body.Total > 0 {
		successRate = float64(body.Successful) / float64(body.Total)
	}
	fmt.Printf("%d requests, %.1f%% successful, %d credits used\n", body.Total, successRate*100, body.Credits)
}
```

{% endtab %}

{% tab title="C#" %}

```csharp
using System.Net.Http.Headers;
using System.Text.Json;

using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(30) };
client.DefaultRequestHeaders.Authorization =
    new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("WEB_SCRAPER_API_TOKEN"));

using var usage = JsonDocument.Parse(
    await client.GetStringAsync("https://scrape.iproyal.com/v1/usage?date_from=2026-09-01&date_to=2026-09-30"));
var root = usage.RootElement;

var total = root.GetProperty("total").GetInt64();
var successRate = total > 0 ? (double)root.GetProperty("successful").GetInt64() / total : 0;
Console.WriteLine($"{total} requests, {successRate * 100:F1}% successful, {root.GetProperty("credits").GetInt64()} credits used");
```

{% endtab %}
{% endtabs %}

### Response

```json
{
  "date_from": "2026-09-01",
  "date_to": "2026-09-30",
  "total": 1580,
  "successful": 1492,
  "failed": 88,
  "credits": 1492,
  "latency": 6840,
  "by_request_type": {
    "page": 1210,
    "serp": 320,
    "image": 50
  },
  "by_status": {
    "success": 1492,
    "bot_blocked": 61,
    "no_data_extracted": 9,
    "target_unavailable": 12,
    "upstream_unavailable": 6
  }
}
```

| Field             | Type           | Description                                                                      |
| ----------------- | -------------- | -------------------------------------------------------------------------------- |
| `date_from`       | string or null | The start day you sent. `null` if you did not send one.                          |
| `date_to`         | string or null | The end day you sent. `null` if you did not send one.                            |
| `total`           | integer        | Requests in the range                                                            |
| `successful`      | integer        | Requests that delivered content                                                  |
| `failed`          | integer        | `total` minus `successful`                                                       |
| `credits`         | integer        | Credits used. Failed requests are refunded, so this usually equals `successful`. |
| `latency`         | integer        | Average processing time per request, in milliseconds                             |
| `by_request_type` | object         | Requests per type: `page` for `universal`, `serp` for `google`, and `image`      |
| `by_status`       | object         | Requests per status. See the table below.                                        |

Types and statuses with no requests are left out of `by_request_type` and `by_status`. To get the success rate, divide `successful` by `total`.

#### Request Statuses

| Status                 | Meaning                                                                        | API Response               | Charged |
| ---------------------- | ------------------------------------------------------------------------------ | -------------------------- | ------- |
| `success`              | The content was delivered, including target pages that answered `404` or `410` | `200`                      | Yes     |
| `bot_blocked`          | The target website's anti-bot protection blocked the request                   | `422 blocked`              | No      |
| `no_data_extracted`    | `parse` was on, but no structured data was found                               | `422 no_data_extracted`    | No      |
| `not_found`            | No image was found at the URL                                                  | `404 not_found`            | No      |
| `target_unavailable`   | The target website was down or did not respond                                 | `502 upstream_unavailable` | No      |
| `rate_limited`         | The service was at full capacity                                               | `503 capacity_exceeded`    | No      |
| `upstream_unavailable` | The request could not be completed on IPRoyal's side                           | `502 upstream_unavailable` | No      |

#### What Is Counted

Usage counts requests that reached the scraping stage. Requests rejected up front are not counted. This covers validation, authentication, balance, and [concurrency limit](https://docs.iproyal.com/scraping-tools/web-scraper-api-beta/making-a-request.md#limits) errors.

A finished request appears in usage after a few seconds.

### Errors

| HTTP Status | `error.code`                              | When                                                                           |
| ----------- | ----------------------------------------- | ------------------------------------------------------------------------------ |
| `400`       | `invalid_request`                         | A date is not a valid `YYYY-MM-DD` day, or `date_from` is later than `date_to` |
| `401`       | `invalid_token`                           | The token is missing or not recognized                                         |
| `403`       | `account_suspended` or `account_disabled` | Your account cannot make requests                                              |
| `502`       | `upstream_unavailable`                    | Usage data is temporarily unavailable. Retry later.                            |


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.iproyal.com/scraping-tools/web-scraper-api-beta/api/usage.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
