# API / JSON scraper (`pocesar/json-downloader`) Actor

Scrape any API / JSON URLs directly to the dataset, and return them in CSV, XML, HTML, or Excel formats. Transform and filter the output.
Enables you to follow pagination recursively from the payload without the need to visit the HTML page.

- **URL**: https://apify.com/pocesar/json-downloader.md
- **Developed by:** [Paulo Cesar](https://apify.com/pocesar) (community)
- **Categories:** Developer tools, Automation, Integrations
- **Stats:** 550 total users, 6 monthly users, 0.0% runs succeeded, 10 bookmarks
- **User rating**: No ratings yet

## Pricing

Pay per usage

This Actor is paid per platform usage. The Actor is free to use, and you only pay for the Apify platform usage, which gets cheaper the higher subscription plan you have.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-usage

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## Download and format JSON endpoint data

Download any JSON URLs directly to the dataset, and return them in CSV, XML, HTML, or Excel formats. Transform and filter the output.

### Features

- Optimized, fast and lightweight
- Small memory requirement
- Works only with JSON payloads
- Easy recursion
- Filter and map complex JSON structures
- Comes enabled with helper libraries: lodash, moment
- Full access to your account resources through `Apify` variable
- The run fails if all requests failed

### Handling errors

This scraper is different from cheerio-scraper that you can handle the errors before the `handlePageFunction` fails.
Using the `handleError` input, you can enqueue extra requests before failing, allowing you to recover or trying a different URL.

```js
{
  handleError: async ({ addRequest, request, response, error }) => {
    request.noRetry = error.message.includes('Unexpected') || response.statusCode == 404;

    addRequest({
      url: `${request.url}?retry=true`,
    });
  }
}

```

### Filter Map function

This function can filter, map and enqueue requests at the same time. The difference is that the userData from the current request will pass to the next request.

```js
const startUrls = [{
  url: "https://example.com",
  userData: {
    firstValue: 0,
  }
}];

// assuming the INPUT url above
await Apify.call('pocesar/json-downloader', {
  filterMap: async ({ request, addRequest, data }) => {

    if (request.userData.isPost) {
      // userData will be inherited from previous request
      request.userData.firstValue == 0; 

      // return the data only after the POST request
      return data;
    } else {
      // add the same request, but as a POST
      addRequest({
        url: `${request.url}/?method=post`,
        method: 'POST',
        payload: {
          username: 'username',
          password: 'password',
        },
        headers: {
          'Content-Type': 'application/json',
        },
        userData: {
          isPost: true
        }
      });
      // omit return or return a falsy value will ignore the output
    } 
  },
})
```

### Examples

#### Flatten an object

```js
{
   filterMap: async ({ flattenObjectKeys, data }) => {
     return flattenObjectKeys(data);
   }
}
/**
 * an object like 
 * {
 *    "deep": {
 *       "nested": ["state", "state1"]
 *    } 
 * }
 * 
 * becomes
 * {
 *    "deep.nested.0": "state",
 *    "deep.nested.1": "state1"
 * }
 */
```

#### Submit a JSON API with POST

```jsonc
{
  "startUrls": [
    {
      "url": "https://ow0o5i3qo7-dsn.algolia.net/1/indexes/prod_PUBLIC_STORE/query?x-algolia-agent=Algolia%20for%20JavaScript%20(4.13.0)%3B%20Browser%20(lite)&x-algolia-api-key=0ecccd09f50396a4dbbe5dbfb17f4525&x-algolia-application-id=OW0O5I3QO7",
      "method": "POST",
      "payload": "{\"query\":\"instagram\",\"page\":0,\"hitsPerPage\":24,\"restrictSearchableAttributes\":[],\"attributesToHighlight\":[],\"attributesToRetrieve\":[\"title\",\"name\",\"username\",\"userFullName\",\"stats\",\"description\",\"pictureUrl\",\"userPictureUrl\",\"notice\",\"currentPricingInfo\"]}",
      "headers": {
        "content-type": "application/x-www-form-urlencoded"
      }
    }
  ]
}
```

#### Follow pagination from payload

```js
{
  filterMap: async ({ addRequest, request, data }) => {
    if (data.nbPages > 1 && data.page < data.nbPages) {
      // get the current payload from the input
      const payload = JSON.parse(request.payload);

      // change the page number
      request.payload = { ...payload, page: data.page + 1 };
      // add the request for parsing the next page
      addRequest(request);
    }

    return data;
  }
}
```

#### Omit output if condition is met

```js
{
  filterMap: async ({ addRequest, request, data }) => {
    if (data.hits.length < 10) {
      return;
    }

    return data;
  }
}
```

#### Unwind array of results, each item from the array in a separate dataset item

```js
{
  filterMap: async ({ addRequest, request, data }) => {
    return data.hits; // just return an array from here
  }
}
```

# Actor input Schema

## `startUrls` (type: `array`):

URLs that return application/json as response

## `filterMap` (type: `string`):

Filter and/or map the output before pushing to the dataset. Check the README for more information

## `handleError` (type: `string`):

Called when errors happen. For more information, see the README

## `customData` (type: `object`):

Any custom data to be available inside the filter map function

## `maxRequestsPerCrawl` (type: `integer`):

Leave empty for no limit

## `proxyConfig` (type: `object`):

Proxies are required to download data from the given input URLs

## `force` (type: `boolean`):

Force parsing the content regardless of the JSON header.

## `maxRequestRetries` (type: `integer`):

How many times failed requests should be retried.

## `debugLog` (type: `boolean`):

Display debug messages

## Actor input object example

```json
{
  "startUrls": [
    {
      "url": "https://blockchain.info/latestblock"
    }
  ],
  "filterMap": "async ({ request, response, addRequest, flattenObjectKeys, context, Apify, _, moment, data, input, customData }) => {\n  return { url: request.url, data };\n}",
  "handleError": "async ({ error, request, response, addRequest, _, moment, Apify, input, context }) => {\n  \n}",
  "customData": {},
  "proxyConfig": {
    "useApifyProxy": true
  },
  "force": false,
  "maxRequestRetries": 4,
  "debugLog": false
}
```

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "startUrls": [
        {
            "url": "https://blockchain.info/latestblock"
        }
    ],
    "filterMap": async ({ request, response, addRequest, flattenObjectKeys, context, Apify, _, moment, data, input, customData }) => {
      return { url: request.url, data };
    },
    "handleError": async ({ error, request, response, addRequest, _, moment, Apify, input, context }) => {
      
    },
    "customData": {},
    "proxyConfig": {
        "useApifyProxy": true
    },
    "maxRequestRetries": 4
};

// Run the Actor and wait for it to finish
const run = await client.actor("pocesar/json-downloader").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {
    "startUrls": [{ "url": "https://blockchain.info/latestblock" }],
    "filterMap": """async ({ request, response, addRequest, flattenObjectKeys, context, Apify, _, moment, data, input, customData }) => {
  return { url: request.url, data };
}""",
    "handleError": """async ({ error, request, response, addRequest, _, moment, Apify, input, context }) => {
  
}""",
    "customData": {},
    "proxyConfig": { "useApifyProxy": True },
    "maxRequestRetries": 4,
}

# Run the Actor and wait for it to finish
run = client.actor("pocesar/json-downloader").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "startUrls": [
    {
      "url": "https://blockchain.info/latestblock"
    }
  ],
  "filterMap": "async ({ request, response, addRequest, flattenObjectKeys, context, Apify, _, moment, data, input, customData }) => {\\n  return { url: request.url, data };\\n}",
  "handleError": "async ({ error, request, response, addRequest, _, moment, Apify, input, context }) => {\\n  \\n}",
  "customData": {},
  "proxyConfig": {
    "useApifyProxy": true
  },
  "maxRequestRetries": 4
}' |
apify call pocesar/json-downloader --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,pocesar/json-downloader"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/RQF4PBZGn3n4qrILi/builds/vnBB67hTutFzEXiE7/openapi.json
