AI & ML

How to Get a YouTube API Key and Use the Data API (2026)

· 5 min read
Community Article
Community articles are authored by SitePoint Premium contributors. Content is screened before publication, and SitePoint reserves the right to moderate or remove articles that violate our guidelines. Views expressed are those of the authors and do not necessarily reflect those of SitePoint.

How to Get a YouTube API Key and Use the Data API (2026)

Matthew Duffin
Matthew Duffin
Published in
·Updated:

The AI briefing for Developers

Stay up to date with AI tools, model releases, and developer workflows that matter.

Weekly. Free. One click to leave.

Share this article

How to Get a YouTube API Key and Use the Data API (2026)
SitePoint Premium
Stay Relevant and Grow Your Career in Tech
  • Premium Results
  • Publish articles on SitePoint
  • Daily curated jobs
  • Learning Paths
  • Discounts to dev tools
Start Free Trial

7 Day Free Trial. Cancel Anytime.

You need a YouTube API key the moment your app has to read anything from YouTube: a video's length, its view count, a channel's latest uploads. Getting one takes about five minutes. Using it well takes a little longer, because YouTube changed how its quota works in June 2026, and plenty of guides still describe the old rules.

In this guide we'll get a key, lock it down and test it. Then we'll use it from Node.js for three real jobs: adding up the length of a playlist, listing a channel's videos without spending a search, and estimating what a video earned. Along the way we'll cover what the YouTube API costs (nothing), how the 2026 quota works, and the errors you're most likely to hit.

What You Can Do With a YouTube API Key

A YouTube API key identifies your project to the YouTube Data API v3. With just a key, you can read public data:

  • Video details: title, length, and view, like and comment counts
  • Playlists and the videos in them
  • Channels: name, subscriber count (unless it's hidden) and uploads
  • Public comments and search results

A key isn't enough for anything that touches someone's account. Uploading videos, editing playlists or reading private data needs OAuth 2.0, where the user signs in and grants your app access.

TaskAPI keyOAuth 2.0
Read public video, playlist and channel dataYesYes
Search YouTubeYesYes
Upload or edit videos and playlistsNoYes
Read a user's private videos or their own channel (mine=true)NoYes

How to Get a YouTube API Key

You'll need a Google account. The YouTube Data API is free, so there's nothing to pay for.

  1. Create a project. Go to the Google Cloud console, open the project picker at the top of the page and click New project. Name it after your app and click Create.
  2. Turn on the YouTube Data API v3. With your new project selected, go to APIs & Services > Library, search for "YouTube Data API v3", open it and click Enable.
  3. Create the key. Go to APIs & Services > Credentials, click Create credentials and choose API key. Copy the key Google shows you.
  4. Restrict it. Open the key from the Credentials page. Under API restrictions, choose Restrict key and tick only YouTube Data API v3. Under Application restrictions, choose IP addresses for a key your server uses, or Websites for a key used in the browser. Save.
  5. Keep it out of your code. Put it in an environment variable or a .env file that's listed in .gitignore. SitePoint's guide to setting Node.js environment variables covers the options.

The restrictions matter more than they look. A key is just a string in a URL, and anyone who copies an unrestricted one can spend your daily quota for you. With an API restriction, the key is useless for other Google APIs. With an application restriction, it only works from your server or your site. Changes to restrictions can take up to five minutes to apply, so don't panic if a request fails straight after you save.

Test Your Key

Before writing any code, check the key with a single request. This one asks for the first video ever uploaded to YouTube, and uses the fields parameter to trim the response down to four values:

curl "https://www.googleapis.com/youtube/v3/videos?part=snippet,statistics&id=jNQXAC9IVRw&fields=items(snippet(title,channelTitle,publishedAt),statistics(viewCount))&key=YOUR_API_KEY"

If the key works, you'll get this back:

{
  "items": [
    {
      "snippet": {
        "publishedAt": "2005-04-24T03:31:52Z",
        "title": "Me at the zoo",
        "channelTitle": "jawed"
      },
      "statistics": {
        "viewCount": "447713984"
      }
    }
  ]
}

That request cost 1 unit of your daily quota, which brings us to the question everyone asks.

Is the YouTube API Free?

Yes. There's no charge per request and no paid plan. Instead you get a daily quota, and since June 1, 2026 it's split into separate buckets:

BucketDefault daily allowanceCost per call
Search (search.list)100 calls1 call
Uploads (videos.insert)100 calls1 call
Everything else10,000 units1 unit for most reads, such as videos.list, playlistItems.list, channels.list and commentThreads.list. A few methods cost more, such as 50 for captions.list and thumbnails.set.

Google's quota calculator lists the cost of every method. Quotas reset at midnight Pacific Time. Every request costs at least 1 unit, including requests that fail, so a retry loop around a broken call can use up a day's quota on its own.

If you've read older guides, search is the big change. A search used to cost 100 units out of the same 10,000, so 100 searches emptied your whole day. Uploads were worse still, at about 1,600 units each until December 2025. Now both have their own buckets, and the 10,000 units are left for everything else.

To give you a feel for what 10,000 units buys, here's what each example in this guide costs:

JobCallsUnits
Total length of a 52-video playlist2 playlistItems.list + 2 videos.list4
A channel's 5 newest videos1 channels.list + 1 playlistItems.list2
One video's views, likes and comments1 videos.list1

How to Increase Your YouTube API Quota

You can't pay for more. To go above the defaults, fill in the YouTube API Services Audit and Quota Extension Form, which is linked from Google's page on quota and compliance audits. YouTube first audits your project to check it follows the YouTube API Services Terms of Service, then someone from the API team gets back to you. Google doesn't give a timeline, so apply well before you need the extra quota.

Most projects never need to. The rest of this guide is about getting a lot done with very few units.

Set Up the Project

The examples need Node.js 20.6 or later, for the built-in fetch and the --env-file flag. There are no packages to install. Make a folder with a .env file in it:

YOUTUBE_API_KEY=your-key-here

Every example imports one small helper. It builds the URL, adds your key and turns API errors into readable messages:

// yt.mjs: one small helper for every YouTube Data API v3 call
const API = 'https://www.googleapis.com/youtube/v3'
const KEY = process.env.YOUTUBE_API_KEY

export async function yt(endpoint, params) {
  const url = `${API}/${endpoint}?${new URLSearchParams({ ...params, key: KEY })}`
  const res = await fetch(url)
  const data = await res.json()
  if (!res.ok) {
    const reason = data.error?.errors?.[0]?.reason ?? data.error?.status
    throw new Error(`${res.status} ${reason}: ${data.error?.message}`)
  }
  return data
}

Run any example with node --env-file=.env followed by the file name.

Example 1: Get the Total Length of a Playlist

YouTube doesn't tell you how long a playlist is. To work it out, you need two methods:

  • playlistItems.list returns up to 50 of the playlist's videos per call, plus a nextPageToken when there are more.
  • videos.list takes up to 50 video IDs per call and returns each video's contentDetails.duration.

Durations come back in ISO 8601 format. PT15M33S is 15 minutes 33 seconds, PT1H2M3S adds an hour, and a stream longer than a day looks like P1DT2H3M4S. The toSeconds() function below handles all three.

// playlist-length.mjs: node playlist-length.mjs PLAYLIST_ID
import { yt } from './yt.mjs'

// Every video ID in the playlist, 50 per call (1 unit each)
async function playlistVideoIds(playlistId) {
  const ids = []
  let pageToken
  do {
    const page = await yt('playlistItems', {
      part: 'contentDetails',
      playlistId,
      maxResults: 50,
      ...(pageToken && { pageToken }),
    })
    ids.push(...page.items.map(item => item.contentDetails.videoId))
    pageToken = page.nextPageToken
  } while (pageToken)
  return ids
}

// "PT15M33S", "PT1H2M3S" or "P1DT2H" -> seconds
function toSeconds(iso) {
  const [, d, h, m, s] = iso.match(/^P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$/) ?? []
  return (+d || 0) * 86400 + (+h || 0) * 3600 + (+m || 0) * 60 + (+s || 0)
}

// Durations for 50 videos per call (1 unit each)
async function durations(ids) {
  const seconds = []
  for (let i = 0; i < ids.length; i += 50) {
    const batch = await yt('videos', { part: 'contentDetails', id: ids.slice(i, i + 50).join(',') })
    seconds.push(...batch.items.map(video => toSeconds(video.contentDetails.duration)))
  }
  return seconds
}

const format = total =>
  `${Math.floor(total / 3600)}h ${Math.floor((total % 3600) / 60)}m ${total % 60}s`

const ids = await playlistVideoIds(process.argv[2])
const seconds = await durations(ids)
const total = seconds.reduce((sum, s) => sum + s, 0)

console.log(`${seconds.length} of ${ids.length} videos available`)
console.log(`Total length: ${format(total)}`)
for (const speed of [1.25, 1.5, 2]) {
  console.log(`At ${speed}x: ${format(Math.round(total / speed))}`)
}

Here it is on freeCodeCamp's Full Courses in One Video playlist:

node --env-file=.env playlist-length.mjs PLWKjhJtqVAbnupwRFOq9zGOWjdvPRtCmO
52 of 52 videos available
Total length: 184h 17m 53s
At 1.25x: 147h 26m 18s
At 1.5x: 122h 51m 55s
At 2x: 92h 8m 57s

That's 184 hours of courses for 4 units of quota. Private and deleted videos still show up in a playlist's items, but videos.list doesn't return them, which is why the script prints "52 of 52 videos available". On a playlist with removed videos, the two numbers will differ.

This is the core of the free YouTube playlist length calculator I built on createthat.ai. The live version adds a target time box that works out the speed you need to finish by a deadline, and it accepts channel, video and Shorts links as well as playlists.

Example 2: List a Channel's Videos Without Searching

The obvious way to find a channel's videos is to search for them. Don't: search is now capped at 100 calls a day, and it isn't built to list everything a channel has posted. Every channel has an uploads playlist instead, and you can reach it in two cheap calls:

  1. channels.list with forHandle turns a handle like @freecodecamp into a channel, including the ID of its uploads playlist at contentDetails.relatedPlaylists.uploads.
  2. playlistItems.list on that playlist returns the videos, newest first.
// channel-videos.mjs: node channel-videos.mjs @handle
import { yt } from './yt.mjs'

// 1 unit: the channel and the ID of its uploads playlist
const { items: [channel] } = await yt('channels', {
  part: 'snippet,contentDetails,statistics',
  forHandle: process.argv[2],
})
const uploads = channel.contentDetails.relatedPlaylists.uploads
console.log(`${channel.snippet.title}: ${Number(channel.statistics.videoCount).toLocaleString()} videos`)

// 1 unit: the 5 newest uploads
const { items } = await yt('playlistItems', { part: 'snippet', playlistId: uploads, maxResults: 5 })
for (const item of items) {
  console.log(item.snippet.publishedAt.slice(0, 10), item.snippet.resourceId.videoId, item.snippet.title)
}
node --env-file=.env channel-videos.mjs @freecodecamp
freeCodeCamp.org: 2,341 videos
2026-11-03 lR931Iz8Z6U Vector Databases Full Course for Beginners – Embeddings, Similarity Search & ChromaDB
2026-10-28 cqfl38Ip1ho How Ethical Hackers Actually Break Into Systems
2026-10-27 aZglGvBPQGs Jev Course – Prefill-Only Inference & Decision Models from Scratch
2026-10-23 JGly6PSK5iw Gemini 4 Argon API Crash Course
2026-10-22 gYXLRMycVMk MCP Security Fundamentals Course

Two units, and none of your 100 daily searches. To get every upload rather than the newest five, page through the playlist with the same pageToken loop as Example 1.

Example 3: Get a Video's Stats and Estimate What It Earned

videos.list with part=statistics returns a video's view, like and comment counts. Dislike counts have been private since December 2021 and favoriteCount is always 0, so don't build anything on those. The script also copes with a missing like or comment count, which you'll see on some videos.

This time the fields parameter trims the response to the values we use. That makes the response smaller, but it doesn't change the cost: the call is 1 unit either way.

// video-earnings.mjs: node video-earnings.mjs VIDEO_ID
import { yt } from './yt.mjs'

// 1 unit. "fields" trims the response to what we use (it doesn't change the cost)
const { items: [video] } = await yt('videos', {
  part: 'snippet,statistics',
  id: process.argv[2],
  fields: 'items(snippet(title,publishedAt),statistics(viewCount,likeCount,commentCount))',
})
const { viewCount, likeCount, commentCount } = video.statistics
const views = Number(viewCount)

// RPM: what a creator keeps per 1,000 views, in USD. It swings a lot with niche and audience country
const rpm = { low: 1, high: 4 }
const usd = n => `$${Math.round(n).toLocaleString()}`

console.log(video.snippet.title)
console.log(`${views.toLocaleString()} views, ${likeCount ? Number(likeCount).toLocaleString() : 'hidden'} likes, ` +
  `${commentCount ? Number(commentCount).toLocaleString() : 'no'} comments`)
console.log(`Estimated earnings: ${usd((views / 1000) * rpm.low)} to ${usd((views / 1000) * rpm.high)}`)

Here it is on freeCodeCamp's Learn Python full course, one of the most-watched videos in that playlist:

node --env-file=.env video-earnings.mjs rfscVS0vtbw
Learn Python - Full Course for Beginners [Tutorial]
49,542,832 views, 1,123,599 likes, 46,100 comments
Estimated earnings: $49,543 to $198,171

Treat the last line as a rough range, not an answer. The Data API doesn't share anyone's revenue, so any estimate is views multiplied by an RPM: what a creator keeps per 1,000 views. RPM moves a lot with the topic and where the viewers live, and the estimate assumes the video shows ads, which not every channel does.

How to Stay Under Your Quota

  • Batch your IDs. videos.list takes up to 50 IDs for the same 1 unit as a single ID. Looking up 50 videos one at a time costs 50 times as much.
  • Skip search when you know what you want. Look up channels with forHandle and their videos through playlists. Save your 100 daily searches for when a user actually searches.
  • Cache what doesn't change. A video's title and length rarely change, so keep them for a while instead of asking again on every page load. YouTube's Developer Policies limit how long you can store API data, so read them before you cache anything for days.
  • Don't retry blindly. Failed requests still cost at least 1 unit. Retry on network errors, not on 400 and 403 responses.
  • Ask only for the parts you use. It won't lower the cost, but smaller responses are quicker to fetch and parse.

And sometimes you don't need an API at all. When I built a font tester, I needed a list of Google Fonts. The Google Fonts Developer API would have meant a key and a call on every visit, for a list that barely changes. Instead I generated a file of the 500 most popular fonts once, from Google's public font metadata, and the page loads it like any other file. No key, no quota and nothing to fail.

Common YouTube API Key Errors

When a call fails, the response's error.message and error.details[0].reason tell you why. These are the ones you'll see most:

Error messageReasonFix
API key not valid. Please pass a valid API key.API_KEY_INVALID (400)Check for a typo or a stray space, and make sure you're sending the key you think you are.
YouTube Data API v3 has not been used in project … before or it is disabled.SERVICE_DISABLED (403)Enable YouTube Data API v3 in the project the key belongs to.
Requests from referer … are blocked.API_KEY_HTTP_REFERRER_BLOCKED (403)Add your site to the key's website restrictions, or call the API from a server with an IP-restricted key.
Requests to this API … are blocked.API_KEY_SERVICE_BLOCKED (403)The key's API restrictions don't include YouTube Data API v3. Add it.
The request cannot be completed because you have exceeded your quota.quotaExceeded (403)Wait for the reset at midnight Pacific Time, cut down your calls, or apply for more quota.

For the invalid key error, the full response looks like this:

{
  "error": {
    "code": 400,
    "message": "API key not valid. Please pass a valid API key.",
    "errors": [
      {
        "message": "API key not valid. Please pass a valid API key.",
        "domain": "global",
        "reason": "badRequest"
      }
    ],
    "status": "INVALID_ARGUMENT",
    "details": [
      {
        "@type": "type.googleapis.com/google.rpc.ErrorInfo",
        "reason": "API_KEY_INVALID",
        "domain": "googleapis.com",
        "metadata": {
          "service": "youtube.googleapis.com"
        }
      },
      {
        "@type": "type.googleapis.com/google.rpc.LocalizedMessage",
        "locale": "en-US",
        "message": "API key not valid. Please pass a valid API key."
      }
    ]
  }
}

Frequently Asked Questions

Is the YouTube API key free?

Yes. Creating a key and calling the YouTube Data API costs nothing. You're limited by the daily quota instead, and there's no paid tier: more quota comes through an audit.

Where do I find my YouTube API key?

In the Google Cloud console, select your project and go to APIs & Services > Credentials. Your keys are listed under API keys, with a Show key option next to each one.

Can I use a YouTube API key in front-end JavaScript?

It works, but anyone can read the key from your page. If you do it, restrict the key to your website and to the YouTube Data API v3. A small server route that calls the API for you is safer, and it gives you somewhere to cache results.

How many requests can I make per day?

By default, 100 searches, 100 uploads and 10,000 units for everything else. Most reads cost 1 unit and videos.list takes 50 IDs per call, so that's enough for the details of up to 500,000 videos a day.

Wrapping Up

Getting a YouTube API key is the easy part: one project, one API to enable, one key and two restrictions. The 2026 quota is generous if you work with it:

  • Batch up to 50 IDs per videos.list call.
  • Avoid search when a handle or playlist will do, since search has its own 100-call limit.
  • Cache what doesn't change, and don't call an API for data you can ship as a file.

All three examples together cost 7 units, out of 10,000. From here, try commentThreads.list to pull a video's comments 100 at a time, or extend Example 2 to page through a channel's entire upload history and add it all up with the code from Example 1.

Source: Matthew Duffin · www.sitepoint.com