> 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-history.md).

# Usage History

Returns your individual requests, newest first.

```
GET /v1/usage/history
```

### Query Parameters

| Parameter | Type    | Required | Description                                           |
| --------- | ------- | -------- | ----------------------------------------------------- |
| `limit`   | integer | No       | Items per page, from `1` to `100`. Defaults to `100`. |
| `offset`  | integer | No       | Number of items to skip. Defaults to `0`.             |

The cURL example reads one page. The other examples read every page and remove duplicates.

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

```bash
curl "https://scrape.iproyal.com/v1/usage/history?limit=100&offset=0" \
  -H "Authorization: Bearer $WEB_SCRAPER_API_TOKEN"
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php

const LIMIT = 100;

$seen = [];
$offset = 0;

do {
    $query = http_build_query(['limit' => LIMIT, 'offset' => $offset]);
    $ch = curl_init('https://scrape.iproyal.com/v1/usage/history?' . $query);

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

    $page = json_decode(curl_exec($ch), true);

    foreach ($page['items'] as $item) {
        if (!isset($seen[$item['job_id']])) {
            $seen[$item['job_id']] = true;
            echo $item['created_at'] . ' ' . $item['status'] . ' ' . $item['target'] . PHP_EOL;
        }
    }

    $offset += LIMIT;
} while ($page['count'] === LIMIT);
```

{% endtab %}

{% tab title="Python" %}

```python
import os

import requests

API_URL = "https://scrape.iproyal.com/v1/usage/history"
LIMIT = 100

seen = set()
offset = 0

while True:
    response = requests.get(
        API_URL,
        headers={"Authorization": f"Bearer {os.environ['WEB_SCRAPER_API_TOKEN']}"},
        params={"limit": LIMIT, "offset": offset},
        timeout=30,
    )
    response.raise_for_status()
    page = response.json()

    for item in page["items"]:
        if item["job_id"] not in seen:
            seen.add(item["job_id"])
            print(item["created_at"], item["status"], item["target"])

    if page["count"] < LIMIT:
        break

    offset += LIMIT
```

{% endtab %}

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

```javascript
const LIMIT = 100;
const seen = new Set();

for (let offset = 0; ; offset += LIMIT) {
  const params = new URLSearchParams({ limit: LIMIT, offset });
  const response = await fetch(`https://scrape.iproyal.com/v1/usage/history?${params}`, {
    headers: { Authorization: `Bearer ${process.env.WEB_SCRAPER_API_TOKEN}` },
    signal: AbortSignal.timeout(30_000),
  });

  if (!response.ok) {
    throw new Error(`HTTP ${response.status}`);
  }

  const page = await response.json();

  for (const item of page.items) {
    if (!seen.has(item.job_id)) {
      seen.add(item.job_id);
      console.log(item.created_at, item.status, item.target);
    }
  }

  if (page.count < LIMIT) {
    break;
  }
}
```

{% 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;
import java.util.HashSet;
import java.util.Set;

public class UsageHistoryExample {
    private static final int LIMIT = 100;

    public static void main(String[] args) throws Exception {
        HttpClient client = HttpClient.newHttpClient();
        ObjectMapper mapper = new ObjectMapper();
        Set<String> seen = new HashSet<>();
        int offset = 0;
        int count;

        do {
            HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://scrape.iproyal.com/v1/usage/history?limit=" + LIMIT + "&offset=" + offset))
                .header("Authorization", "Bearer " + System.getenv("WEB_SCRAPER_API_TOKEN"))
                .timeout(Duration.ofSeconds(30))
                .GET()
                .build();

            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            if (response.statusCode() != 200) {
                throw new IllegalStateException("HTTP " + response.statusCode());
            }

            JsonNode page = mapper.readTree(response.body());
            for (JsonNode item : page.get("items")) {
                if (seen.add(item.get("job_id").asText())) {
                    System.out.println(item.get("created_at").asText() + " " + item.get("status").asText() + " " + item.get("target").asText());
                }
            }

            count = page.get("count").asInt();
            offset += LIMIT;
        } while (count == LIMIT);
    }
}
```

{% endtab %}

{% tab title="Go" %}

```go
package main

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

const limit = 100

type historyPage struct {
	Count int `json:"count"`
	Total int `json:"total"`
	Items []struct {
		RequestType    string `json:"request_type"`
		Status         string `json:"status"`
		StatusCode     int    `json:"status_code"`
		Target         string `json:"target"`
		GeoLocation    string `json:"geo_location"`
		JobID          string `json:"job_id"`
		CreditDeducted bool   `json:"credit_deducted"`
		Credits        int    `json:"credits"`
		CreatedAt      string `json:"created_at"`
	} `json:"items"`
}

func main() {
	client := &http.Client{Timeout: 30 * time.Second}
	seen := map[string]bool{}

	for offset := 0; ; offset += limit {
		url := fmt.Sprintf("https://scrape.iproyal.com/v1/usage/history?limit=%d&offset=%d", limit, offset)
		req, _ := http.NewRequest(http.MethodGet, url, nil)
		req.Header.Set("Authorization", "Bearer "+os.Getenv("WEB_SCRAPER_API_TOKEN"))

		resp, err := client.Do(req)
		if err != nil {
			fmt.Println("request failed:", err)
			return
		}

		var page historyPage
		err = json.NewDecoder(resp.Body).Decode(&page)
		resp.Body.Close()
		if resp.StatusCode != http.StatusOK || err != nil {
			fmt.Println("unexpected response, HTTP", resp.StatusCode)
			return
		}

		for _, item := range page.Items {
			if !seen[item.JobID] {
				seen[item.JobID] = true
				fmt.Println(item.CreatedAt, item.Status, item.Target)
			}
		}

		if page.Count < limit {
			return
		}
	}
}
```

{% endtab %}

{% tab title="C#" %}

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

const int Limit = 100;

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

var seen = new HashSet<string>();
var offset = 0;
int count;

do
{
    using var page = JsonDocument.Parse(
        await client.GetStringAsync($"https://scrape.iproyal.com/v1/usage/history?limit={Limit}&offset={offset}"));

    foreach (var item in page.RootElement.GetProperty("items").EnumerateArray())
    {
        if (seen.Add(item.GetProperty("job_id").GetString()!))
        {
            Console.WriteLine($"{item.GetProperty("created_at").GetString()} {item.GetProperty("status").GetString()} {item.GetProperty("target").GetString()}");
        }
    }

    count = page.RootElement.GetProperty("count").GetInt32();
    offset += Limit;
} while (count == Limit);
```

{% endtab %}
{% endtabs %}

### Response

```json
{
  "count": 2,
  "total": 1580,
  "items": [
    {
      "request_type": "page",
      "status": "success",
      "status_code": 200,
      "target": "https://example.com/products/42",
      "geo_location": "de",
      "job_id": "84e647f3-c72f-479b-9285-5c5903cad2dc",
      "credit_deducted": true,
      "credits": 1,
      "created_at": "2026-10-06 09:15:02"
    },
    {
      "request_type": "serp",
      "status": "bot_blocked",
      "status_code": 422,
      "target": "running shoes",
      "geo_location": "",
      "job_id": "7e842747-2a53-440d-aaac-de648bae1c5e",
      "credit_deducted": false,
      "credits": 0,
      "created_at": "2026-10-06 09:14:40"
    }
  ]
}
```

| Field   | Type    | Description                                |
| ------- | ------- | ------------------------------------------ |
| `count` | integer | Items on this page                         |
| `total` | integer | All requests on your account, for all time |
| `items` | array   | Requests, newest first                     |

Each item has these fields:

| Field             | Type    | Description                                                                                                             |
| ----------------- | ------- | ----------------------------------------------------------------------------------------------------------------------- |
| `request_type`    | string  | `page` for `universal`, `serp` for `google`, or `image`                                                                 |
| `status`          | string  | The outcome. [Usage](https://docs.iproyal.com/scraping-tools/web-scraper-api-beta/api/usage.md) lists every status.     |
| `status_code`     | integer | For `success`, the HTTP status the target website returned. Otherwise, the HTTP status IPRoyal returned to you.         |
| `target`          | string  | The URL, or the search keywords for `serp`                                                                              |
| `geo_location`    | string  | The country code you sent. Empty if you did not send one.                                                               |
| `job_id`          | string  | The `job_id` from the [Scraping](https://docs.iproyal.com/scraping-tools/web-scraper-api-beta/api/scraping.md) response |
| `credit_deducted` | boolean | Whether the request was charged                                                                                         |
| `credits`         | integer | Credits charged for the request: `1` or `0`                                                                             |
| `created_at`      | string  | When the request started, in UTC, as `YYYY-MM-DD HH:MM:SS`                                                              |

### Pagination

Increase `offset` by `limit` until `count` is less than `limit`.

New requests appear at the top of the list. If you page while you are scraping, an item can show up on two pages. Remove duplicates by `job_id`.

### Retention and Freshness

Usage History keeps requests from the last 12 months. `total` counts all requests, including older ones that are no longer listed.

A finished request appears in the history after a few seconds. Only requests that reached the scraping stage are listed. Requests rejected up front never appear and are never charged.

### Errors

| HTTP Status | `error.code`                              | When                                                     |
| ----------- | ----------------------------------------- | -------------------------------------------------------- |
| `400`       | `invalid_request`                         | `limit` is outside `1` to `100`, or `offset` is negative |
| `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-history.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.
