# YouTube Search API — Videos, Channels & Playlists (`gauravlabs/youtube-search-api`) Actor

Scrape YouTube search results by keyword. Extract videos, channels, playlists, Shorts shelves, views and thumbnails. Filters, country/language settings and pagination. Pay per successful request, not result.

- **URL**: https://apify.com/gauravlabs/youtube-search-api.md
- **Developed by:** [Gaurav Kumar Choudhary](https://apify.com/gauravlabs) (community)
- **Categories:** Social media, Videos, Marketing
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

$2.00 / 1,000 successful youtube search requests

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

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

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

## YouTube Search API — Videos, Channels & Playlists

### At a glance

- Collect: YouTube search cards for videos, channels or playlists.
- Input: use the runnable example below or the prefilled Input form.
- Output: the default dataset supports JSON/CSV/Excel export; see output modes below.
- Billing: $2 per 1,000 successful search-page requests, with all returned cards included. No startup fee. Platform usage may be additional.
- Limits: Search metadata is not full video enrichment. No video downloads, transcript extraction or full comments.

Search YouTube by keyword and export structured video, channel and playlist search results. Research content topics, discover creators, compare search visibility and build automated data pipelines without supplying a YouTube Data API key or proxy configuration.

### Pricing: $2 per 1,000 successful requests

One successful search-page request costs **$0.002**, with all returned results included. No startup fee and no extra per-video charge. Each additional successful pagination request costs another $0.002. Valid searches with zero matches are still successful billable requests; invalid inputs and failed fetches are not charged by this Actor. Apify platform charges, if applicable, are separate.

Example: 100 requests returning 20 video rows each cost $0.20 for 2,000 videos. Counts vary, so this is an illustration, not a result-count guarantee.

### Quick start

```json
{"queries":["python tutorial","budget travel"],"maxRequests":2,"maxPagesPerQuery":1,"hl":"en","gl":"us"}
```

For channel discovery use `searchPreset: "channels"`; for playlist search use `"playlists"`. Sorting and date, duration, quality or live filters are available as presets. Select one preset at a time; advanced combinations require a valid YouTube `sp` token. Tokens can change and YouTube may silently ignore outdated filters.

#### Compact video mode

```json
{"queries":["python tutorial"],"num":30,"maxRequests":1}
```

Get up to 30 videos in a single request. Compact mode cannot combine with any filter preset, `sp`, or multiple pages. It omits mixed channel/playlist/Shorts cards, snippets and pagination; view counts may be rounded. Fewer videos can be returned when the feed runs out. `truncated` flags internal truncation when reported.

#### Standard mode and pagination

Omit `num` for standard search metadata and mixed results. Increase `maxPagesPerQuery` to follow continuation pages, or resume one keyword using `sp` from `SUMMARY.pages[].nextPageToken`. The global `maxRequests` cap includes failed attempts and prevents unbounded paging. Duplicate keywords and duplicate rows within the same result bucket across pages are skipped.

### Output

The default dataset contains one row per returned item. Export JSON, CSV, Excel or XML using Apify. Fields include `query`, `recordType`, `sourceBucket`, `title`, `link`, `video_id`, `views`, `views_original`, `length`, `published_date`, `description`, `channel`, `thumbnail`, `subscribers`, `video_count`, `live`, `page`, `fetchedAt` and `metadataMode`. Fields depend on the result type and may be null.

`SUMMARY` in the default key-value store records request counts, row counts, per-page continuation tokens, truncation, safe failure messages and budget stopping. Recommendation shelves are included by default; ads are opt-in. Shorts shelves appear only when YouTube supplies them.

### API and automation

Call this Actor through Apify's API with its Actor ID or `gauravlabs~youtube-search-api`. Integrate dataset exports into n8n, Make, Zapier or your own scripts. Schedule runs in Apify to track the same keywords over time.

### Scope and limitations

This is a **keyword search scraper**, not a full channel crawler, video-details extractor, complete playlist downloader, comments API, transcript API or media downloader. Channel and playlist results are search cards, not complete inventories. Captions filtering finds captioned videos; it does not extract transcripts. No likes or comment counts are promised. Search snippets are not full video descriptions. Results change with locale, time and YouTube experiments; availability and ordering are not guaranteed. Relative published dates remain localized text. No lifetime free-account quota is advertised or implemented.

### Support and custom use cases

Open an Actor issue or contact Gaurav Labs through the developer profile for setup help, custom workflows, additional data sources or specific business requirements. Include your run ID and non-sensitive input. Never post credentials.

Independent tool; not affiliated with, endorsed by or an official API of YouTube or Google. Use public data responsibly and comply with applicable terms and laws.

### Minimal API example

Store your own Apify token in `APIFY_TOKEN`; never paste it into public input or code. This example uses the same small input as the prefilled form.

```python
import os
import requests

response = requests.post(
    "https://api.apify.com/v2/acts/gauravlabs~youtube-search-api/run-sync-get-dataset-items",
    headers={"Authorization": "Bearer " + os.environ["APIFY_TOKEN"]},
    json={"queries":["python tutorial"]},
    timeout=300,
)
response.raise_for_status()
print(response.json())
```

For large batches, start an asynchronous run with `/runs`, wait for its final status, and retrieve its default dataset. HTTP success when starting a run does not prove the extraction succeeded.

#### Minimal output shape (illustrative)

The following shows one documented field, not a fresh result or a promised yield. Inspect the output reference above for the complete schema.

```json
{
  "metadataMode": "standard"
}
```

### Practical workflow and accuracy notes

Creator discovery: use `searchPreset: "channels"`. Video research: use standard search for richer cards or `num` for compact videos. Playlist discovery: use `searchPreset: "playlists"`. `views_original` preserves available source text and may be rounded; search metadata is not verified current channel/video analytics.

# Actor input Schema

## `queries` (type: `array`):

Keyword searches, not video or channel URLs. Duplicate keywords are skipped.

## `searchPreset` (type: `string`):

Choose one preset. Presets cannot be combined. Advanced combinations require a valid sp token.

## `num` (type: `integer`):

1–30 videos in one request. Omit for standard metadata and mixed results. Cannot combine with filters, sp, or multiple pages. Counts can be rounded; snippets and pagination are unavailable.

## `maxPagesPerQuery` (type: `integer`):

Each successful page is one billable request. Requires standard mode (omit num). Stops when no continuation is available.

## `maxRequests` (type: `integer`):

Global cap across all keywords and pages, including failed attempts. Not a lifetime account quota.

## `hl` (type: `string`):

Example en, de, fr, es, hi. Controls localized metadata text.

## `gl` (type: `string`):

Two-letter lowercase code, e.g. us, gb, in, de. Influences ranking.

## `device` (type: `string`):

YouTube desktop or mobile search layout.

## `includeShorts` (type: `boolean`):

Best-effort standard-mode shelves, not a dedicated Shorts search.

## `includeDiscovery` (type: `boolean`):

Include recommendation shelves when supplied.

## `includeAds` (type: `boolean`):

Include promoted search entries when supplied.

## `sp` (type: `string`):

Optional opaque YouTube token. Requires one keyword and Mixed results preset. Cannot combine with num. Use nextPageToken from SUMMARY to resume.

## `requestTimeoutSecs` (type: `integer`):

No automatic Actor retries; failed requests are not charged by this Actor.

## Actor input object example

```json
{
  "queries": [
    "python tutorial"
  ],
  "searchPreset": "all",
  "maxPagesPerQuery": 1,
  "maxRequests": 10,
  "hl": "en",
  "gl": "us",
  "device": "desktop",
  "includeShorts": true,
  "includeDiscovery": true,
  "includeAds": false,
  "requestTimeoutSecs": 90
}
```

# Actor output Schema

## `results` (type: `string`):

No description

## `summary` (type: `string`):

No description

# 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 = {
    "queries": [
        "python tutorial"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("gauravlabs/youtube-search-api").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 = { "queries": ["python tutorial"] }

# Run the Actor and wait for it to finish
run = client.actor("gauravlabs/youtube-search-api").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 '{
  "queries": [
    "python tutorial"
  ]
}' |
apify call gauravlabs/youtube-search-api --silent --output-dataset

```

## MCP server setup

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

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/pCalaofI9W3PauYRn/builds/oN7pCmN4uJg6y9aZv/openapi.json
