YouTube Search
Keyword search over YouTube videos with relevance or popularity sorting, upload-date filters and cursor pagination.
- Price per call
- 2 credits
- per successful call
- Price ceiling
- 16 credits
- if a call is retried elsewhere
- Failed calls
- Free
- retried automatically
- Billed
- Per call
- only on success
Endpoint
api.primaryapi.com/ v1/ run/ youtube. searchAuth: API key with run or full access, or a dashboard session
Send the input below as a JSON body. The call is routed to a healthy upstream; if an attempt fails, it is retried automatically inside the same request and you pay only for the answer you get. To check an input and see the exact price without running anything, call POST /v1/quote/youtube.search with the same body (free).
Example request
curl -sS -X POST "https://api.primaryapi.com/v1/run/youtube.search" \
-H "Authorization: Bearer $PRIMARYAPI_API_KEY" \
-H "Content-Type: application/json" \
-d '{"query":"running shoes review"}'const res = await fetch('https://api.primaryapi.com/v1/run/youtube.search', {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.PRIMARYAPI_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
query: 'running shoes review',
}),
});
const body = await res.json();
if (!res.ok) throw new Error(`${body.code}: ${body.error}`);
// found:false is a successful answer ("does not exist"), not an error
console.log(body.output.found ? body.output.data : body.output.reason, body.credits);import os
import requests
res = requests.post(
"https://api.primaryapi.com/v1/run/youtube.search",
headers={"Authorization": f"Bearer {os.environ['PRIMARYAPI_API_KEY']}"},
json={
"query": "running shoes review",
},
timeout=60,
)
body = res.json()
if not res.ok:
raise RuntimeError(f"{body['code']}: {body['error']}")
# found=False is a successful answer ("does not exist"), not an error
print(body["output"]["data"] if body["output"]["found"] else body["output"]["reason"], body["credits"]){
"name": "run_api",
"arguments": {
"sku": "youtube.search",
"input": {
"query": "running shoes review"
}
}
}Price this exact input first (free)
curl -sS -X POST "https://api.primaryapi.com/v1/quote/youtube.search" \
-H "Authorization: Bearer $PRIMARYAPI_API_KEY" \
-H "Content-Type: application/json" \
-d '{"query":"running shoes review"}'Returns credits (what the call is expected to cost) and maxCredits (the most it can cost, which is set aside while it runs). Invalid input fails here the same way it would on run.
Input
JSON body fields. Unknown fields are rejected with 400 invalid_input (never silently ignored). You may add the routing controls preferLatencyUnderMs and maxCredits to the same object.
querystringrequired- Search keywords, as typed into the YouTube search box.max 500 chars
sortByenumdefault"relevance"- Sort order: relevance (default) or popular (most viewed).one of: relevance, popular
uploadDateenum- Only videos uploaded today, this week, this month or this year. Omit for any time.one of: today, this_week, this_month, this_year
limitintegerdefault20- Maximum number of results to return (1-50, default 20).1–50
cursorstring- Opaque pagination cursor: pass the previous response's nextCursor.
requireCursorboolean- Set true when you intend to page: the call is then served only by sources that return a nextCursor (AnyAPI-compatible flag).
Output
When output.found is true, output.data has these fields (a list under videos, billed per item returned).
videosobject[]videos[].idstring- 11-character video ID
videos[].urlstring- Watch URL
videos[].titlestring | nullvideos[].imagestring | null- Thumbnail URL
videos[].viewsinteger | nullvideos[].lengthTextstring | null- Duration label as YouTube shows it, e.g. "4:14"
videos[].durationSecondsinteger | nullvideos[].publishedTimestring | null- Relative publish label, e.g. "2 years ago"
videos[].createdUtcstring | null- Publish time, ISO 8601 (best effort; null when the source only gives a relative label)
videos[].channelstring | null- Channel title
videos[].channelTitlestring | null- Channel title (same value as channel; AnyAPI hashtag-search naming)
videos[].authorIdstring | null- Channel ID (UC…)
videos[].authorHandlestring | null- Channel handle without @
videos[].authorAvatarUrlstring | nullnextCursorstring | null
TypeScript type
/** output.data when output.found is true */
type YoutubeSearch = {
videos: {
/** 11-character video ID */
id: string;
/** Watch URL */
url: string;
title: string | null;
/** Thumbnail URL */
image: string | null;
views: number | null;
/** Duration label as YouTube shows it, e.g. "4:14" */
lengthText: string | null;
durationSeconds: number | null;
/** Relative publish label, e.g. "2 years ago" */
publishedTime: string | null;
/** Publish time, ISO 8601 (best effort; null when the source only gives a relative label) */
createdUtc: string | null;
/** Channel title */
channel: string | null;
/** Channel title (same value as channel; AnyAPI hashtag-search naming) */
channelTitle: string | null;
/** Channel ID (UC…) */
authorId: string | null;
/** Channel handle without @ */
authorHandle: string | null;
authorAvatarUrl: string | null;
}[];
nextCursor: string | null;
};If what you asked about does not exist, is private, or a search matches nothing, the call still succeeds: output.found is false, output.data is null and output.reason says why. Such misses are free unless the notes below say misses are billed, in which case a miss costs the price of one call.
Pagination. Pass the previous response’s nextCursor as cursor to get the next page. nextCursor: null means there is nothing more. See Pagination.
Example response
Values are placeholders that follow the output schema (strings as "string", numbers as 0); credits shows what this call would cost at the usual price.
{
"output": {
"found": true,
"data": {
"videos": [
{
"id": "BzSzwqb-OEE",
"url": "https://www.youtube.com/watch?v=BzSzwqb-OEE",
"title": "NF - RUNNING (Audio)",
"image": "https://i.ytimg.com/vi/BzSzwqb-OEE/hq720.jpg",
"views": 14860541,
"lengthText": "4:14",
"durationSeconds": 254,
"publishedTime": "2 years ago",
"createdUtc": "2023-05-28T17:08:46.499Z",
"channel": "NFrealmusic",
"channelTitle": "NFrealmusic",
"authorId": "UCoRR6OLuIZ2-5VxtnQIaN2w",
"authorHandle": null,
"authorAvatarUrl": "https://yt3.ggpht.com/J1_Si0TYNZ-991v09y8RpCh4_Z_ALwKmPgMYnJqjNhoglVtipf3oEN8LpzG1kS0qsv8Jptpmmg=s88-c-k-c0x00ffffff-no-rj"
}
],
"nextCursor": "eyJsIjoieW91dHViZS5zZWFyY2gjc2NyYXBlY3JlYXRvcnMiLCJ0IjoiRW9vREVnLi4uIn0"
}
},
"provider": "PrimaryAPI",
"credits": 2,
"items": 1,
"requestId": "req_01JBXK6Y2N9V8T4R3Q2P1M0A7Z",
"nextCursor": null
}Pricing and reliability
Calls go only to upstreams that are healthy right now. If an attempt fails, the call is retried automatically inside the same request; a failed attempt costs nothing, and a call never costs more than its quote’s maxCredits. Live figures below are measured on real traffic.
Success rate, uptime, latency and call counts are measured live from real traffic over 30 days and show “—” until there is data.
Errors
Errors are JSON { code, error, requestId } and are never charged. The ones to handle for this endpoint:
- invalid_inputThe request failed validation before anything ran.
- unauthorizedNo valid API key or session was presented.
- insufficient_balanceThe balance cannot cover the most this call could cost.
- key_limit_reachedThe key’s own spend limit is used up for the current window.
- trial_cap_reachedAn agent trial key has used its whole trial budget.
- forbiddenThe credential is valid but may not do this.
- not_foundThe thing addressed by the URL does not exist for you.
- idempotency_conflictThe
Idempotency-Keyis already bound to a different request. - rate_limitedToo many requests in the current window.
- all_sources_failedThe call could not be answered, even after automatic retries.
- service_unavailableThis API cannot run in this deployment right now.
- timeoutThe request passed its deadline before it finished.
More YouTube endpoints
- YouTube Channel1 credit
- YouTube Channel Live Streams2 credits
- YouTube Channel Public Email1 credit
- YouTube Channel Search2 credits
- YouTube Channel Shorts2 credits
- YouTube Channel Videos1 credit
- YouTube Hashtag Search2 credits
- YouTube Shorts Search2 credits
- YouTube Video2 credits
- YouTube Video Comments2 credits
- YouTube Video Transcript2 credits
- YouTube Video Transcript (Provenance)3 credits
- YouTube Channel Community PostsPlanned
- YouTube Channel Contact EmailPlanned
- YouTube Channel PlaylistsPlanned
- YouTube Comment RepliesPlanned
- YouTube Community PostPlanned
- YouTube PlaylistPlanned
- YouTube Trending ShortsPlanned
- YouTube Video SponsorsPlanned
Generated from the PrimaryAPI catalog. Machine-readable contract: GET https://api.primaryapi.com/v1/apis/youtube.search.