YouTube API Full avatar

YouTube API Full

Pricing

from $10.00 / 1,000 api requests

Go to Apify Store
YouTube API Full

YouTube API Full

A Standby HTTP API for YouTube search, video metadata, channel details, comments, playlists, trending videos, and related public YouTube data.

Pricing

from $10.00 / 1,000 api requests

Rating

0.0

(0)

Developer

Kevin JAMEIN

Kevin JAMEIN

Maintained by Community

Actor stats

0

Bookmarked

1

Total users

0

Monthly active users

44 minutes ago

Last modified

Share

🎥 YouTube API Full v2.0

Version Node LICENSE Security

API YouTube professionnelle, sécurisée et hautement performante. Prête pour la production et RapidAPI.

✨ Caractéristiques

  • 🔒 Sécurisé : 0 vulnérabilité, clés protégées, validation complète
  • Performant : Cache intelligent (-80% appels API), compression, optimisations
  • 📚 Documenté : Swagger UI interactif intégré
  • 🛡️ Protégé : Rate limiting sur 3 niveaux, gestion d'erreurs avancée
  • 🐳 Production Ready : Docker, logging Winston, monitoring
  • 💰 Monétisable : Prêt pour RapidAPI

📋 Table des Matières


🚀 Installation Rapide

Prérequis

  • Node.js >= 16.0.0
  • npm ou yarn
  • Clé API YouTube (obtenir ici)

Installation en 3 étapes

# 1. Installer les dépendances
npm install
# 2. Configurer
cp ENV_TEMPLATE.txt .env
# Éditer .env et ajouter votre YOUTUBE_API_KEY
# 3. Démarrer
npm start

Votre API est accessible sur : http://localhost:3000

Documentation interactive : http://localhost:3000/api-docs


⚙️ Configuration

Variables d'Environnement

Créez un fichier .env à la racine :

# Serveur
NODE_ENV=production
PORT=3000
# API Keys (OBLIGATOIRE)
YOUTUBE_API_KEY=votre_clé_youtube_ici
# CORS (production : liste d'origines séparées par virgules)
# Laisser vide pour bloquer toutes les origines cross-origin en production
CORS_ORIGINS=https://votre-app.com,https://autre-domaine.com
# Administration (optionnel - si défini, protège /admin/* avec x-admin-key header)
ADMIN_API_KEY=votre_clé_admin_secrète
# Cookies YouTube (optionnel - pour contenu restreint par âge)
YT_COOKIE=votre_cookie
YT_TOKEN=votre_token
YT_LANG=en # Langue ytdl (défaut: en)
# Cache (en secondes)
CACHE_TTL=3600
CACHE_CHECK_PERIOD=600
# Rate Limiting
RATE_LIMIT_WINDOW_MS=900000
RATE_LIMIT_MAX_REQUESTS=100
# Logging
LOG_LEVEL=info

Obtenir une Clé API YouTube

  1. Allez sur Google Cloud Console
  2. Créez un projet
  3. Activez "YouTube Data API v3"
  4. Créez une clé API dans "Identifiants"
  5. Copiez la clé dans votre .env

💻 Utilisation

Démarrage

# Mode production
npm start
# Mode développement (auto-reload)
npm run dev
# Tests
npm test
# Linting
npm run lint
npm run lint:fix

Vérification

# Health check
curl http://localhost:3000/health
# Statistiques du cache (sans clé admin, ou avec si ADMIN_API_KEY est défini)
curl http://localhost:3000/admin/cache/stats
curl -H "x-admin-key: votre_clé" http://localhost:3000/admin/cache/stats
# Documentation Swagger interactive
# Ouvrir dans le navigateur : http://localhost:3000/api-docs

📡 API Endpoints

🔍 Recherche

EndpointMéthodeDescription
/api/search/videosGETRechercher des vidéos (filtres durée, définition, ordre)
/api/search/channelsGETRechercher des chaînes
/api/search/playlistsGETRechercher des playlists
/api/search/moviesGETRechercher des films
/api/search/episodesGETRechercher des épisodes TV
/api/search/allGETRecherche combinée vidéos + chaînes + playlists
/api/hashtagGETRecherche par hashtag

Paramètre commun : pageToken disponible sur tous ces endpoints pour paginer.

Exemple :

curl "http://localhost:3000/api/search/videos?query=nodejs&maxResults=10&order=viewCount"
# Page suivante
curl "http://localhost:3000/api/search/videos?query=nodejs&pageToken=NEXT_PAGE_TOKEN"
# Recherche multi-types (vidéos + chaînes + playlists en une requête)
curl "http://localhost:3000/api/search/all?query=javascript&regionCode=FR"

📺 Vidéos

EndpointMéthodeDescription
/api/videosGETDétails complets (id, part)
/api/videoStatsGETStatistiques (vues, likes, commentaires)
/api/videoStatusGETStatut upload et confidentialité
/api/videoPlayerGETCode embed iframe
/api/videoTopicsGETTopics Freebase
/api/videoCategoriesGETCatégories par région
/api/captionsGETPistes de sous-titres
/api/trendingGETVidéos tendances par pays

Exemple :

curl "http://localhost:3000/api/videoStats?id=dQw4w9WgXcQ"
# Tendances françaises (utilise chart=mostPopular)
curl "http://localhost:3000/api/trending?geo=FR&maxResults=20"
# Catégories disponibles en France
curl "http://localhost:3000/api/videoCategories?regionCode=FR&hl=fr"
# Sous-titres d'une vidéo
curl "http://localhost:3000/api/captions?videoId=dQw4w9WgXcQ"

📢 Chaînes

EndpointMéthodeDescription
/api/channelsByIdsGETInfos par ID(s), virgule pour plusieurs
/api/channelByUsernameGETInfos par handle (@username)
/api/channelSectionsGETSections de la page chaîne
/api/channelSectionsByIdGETSection spécifique par ID
/api/activitiesGETFil d'activités de la chaîne
/api/subscriptionsGETAbonnements de la chaîne

💬 Commentaires

EndpointMéthodeDescription
/api/commentsGETFils de commentaires d'une vidéo
/api/commentRepliesGETRéponses à un commentaire
/api/commentGETCommentaire spécifique par ID

📋 Playlists

EndpointMéthodeDescription
/api/playlistsGETPlaylists d'une chaîne
/api/playlistCodeGETCode embed iframe des playlists
/api/playlistItemsGETVidéos contenues dans une playlist

Exemple :

$curl "http://localhost:3000/api/playlistItems?playlistId=PLxxxxxx&maxResults=50"

💾 Téléchargement

EndpointMéthodeDescription
/api/downloadPOSTMétadonnées + URLs de streaming directes

Body parameters :

ParamètreRequisDescription
urlURL YouTube complète
cookieCookie de session YouTube (pour contenu restreint)
poTokenProof of Origin Token YouTube
visitorDataVisitor Data YouTube

Exemple :

curl -X POST http://localhost:3000/api/download \
-H "Content-Type: application/json" \
-d '{"url": "https://www.youtube.com/watch?v=VIDEO_ID"}'

La réponse contient data.formats.videoWithAudio (vidéo+audio) et data.formats.audioOnly.

⚠️ Limitation connue — hébergements cloud (Vercel, Railway, Heroku…)

YouTube bloque les requêtes provenant d'IPs de data center. Sur ces plateformes, /api/download retournera Sign in to confirm you're not a bot même avec des cookies valides, car le poToken doit être généré depuis la même IP résidentielle que celle effectuant la requête.

Contournement : passer cookie, poToken et visitorData directement dans le body, obtenus depuis un navigateur sur IP résidentielle (DevTools > Network > requête youtubei.googleapis.com/youtubei/v1/player).

Cet endpoint fonctionne sans restriction en auto-hébergement sur une IP résidentielle ou un VPS non bloqué.

🔧 Administration

EndpointMéthodeDescription
/healthGETHealth check
/admin/cache/statsGETStats cache (header x-admin-key requis si ADMIN_API_KEY configuré)
/admin/cache/clearPOSTVider cache (?pattern= optionnel)
# Si ADMIN_API_KEY est configuré
curl -H "x-admin-key: votre_clé" http://localhost:3000/admin/cache/stats
# Vider uniquement les entrées de recherche
curl -X POST -H "x-admin-key: votre_clé" \
"http://localhost:3000/admin/cache/clear?pattern=youtube:search"

Format de Réponse

Succès :

{
"success": true,
"data": { ... }
}

Erreur :

{
"success": false,
"error": {
"code": 400,
"message": "Description de l'erreur"
}
}

💡 Exemples de Code

JavaScript / Node.js

const axios = require('axios');
const BASE_URL = 'http://localhost:3000/api';
// Rechercher des vidéos
async function searchVideos(query) {
const response = await axios.get(`${BASE_URL}/search/videos`, {
params: { query, maxResults: 10 }
});
return response.data;
}
// Télécharger une vidéo
async function downloadVideo(url) {
const response = await axios.post(`${BASE_URL}/download`, { url });
return response.data;
}
// Statistiques vidéo
async function getVideoStats(videoId) {
const response = await axios.get(`${BASE_URL}/videoStats`, {
params: { id: videoId }
});
return response.data;
}
// Utilisation
searchVideos('nodejs tutorial').then(data => console.log(data));

Python

import requests
BASE_URL = 'http://localhost:3000/api'
# Rechercher des vidéos
def search_videos(query, max_results=10):
response = requests.get(f'{BASE_URL}/search/videos',
params={'query': query, 'maxResults': max_results})
return response.json()
# Télécharger une vidéo
def download_video(url):
response = requests.post(f'{BASE_URL}/download',
json={'url': url})
return response.json()
# Statistiques
def get_video_stats(video_id):
response = requests.get(f'{BASE_URL}/videoStats',
params={'id': video_id})
return response.json()
# Utilisation
videos = search_videos('python programming')
print(videos)

PHP

<?php
$baseUrl = 'http://localhost:3000/api';
// Rechercher des vidéos
function searchVideos($query, $maxResults = 10) {
global $baseUrl;
$url = "$baseUrl/search/videos?" . http_build_query([
'query' => $query,
'maxResults' => $maxResults
]);
return json_decode(file_get_contents($url), true);
}
// Utilisation
$videos = searchVideos('php tutorial');
print_r($videos);
?>

cURL

# Rechercher
curl "http://localhost:3000/api/search/videos?query=javascript&maxResults=5"
# Télécharger
curl -X POST http://localhost:3000/api/download \
-H "Content-Type: application/json" \
-d '{"url": "https://www.youtube.com/watch?v=VIDEO_ID"}'
# Statistiques
curl "http://localhost:3000/api/videoStats?id=VIDEO_ID"
# Tendances
curl "http://localhost:3000/api/trending?geo=FR"

🐳 Déploiement

Docker

# Build
docker build -t youtube-api .
# Run
docker run -p 3000:3000 --env-file .env youtube-api
# Ou avec Docker Compose
docker-compose up -d

Heroku

# Créer l'app
heroku create youtube-api-votre-nom
# Configurer
heroku config:set YOUTUBE_API_KEY=votre_clé
heroku config:set NODE_ENV=production
# Déployer
git push heroku main
# Voir les logs
heroku logs --tail

Vercel

# Installer Vercel CLI
npm i -g vercel
# Déployer
vercel --prod
# Configurer les variables
vercel env add YOUTUBE_API_KEY
vercel env add NODE_ENV

DigitalOcean / AWS / GCP

Utilisez Docker ou déployez directement avec Node.js :

# Sur votre serveur
git clone <votre-repo>
cd youtube-api-full
npm install --production
cp ENV_TEMPLATE.txt .env
# Éditer .env
# Avec PM2 (recommandé)
npm install -g pm2
pm2 start server.js --name youtube-api
pm2 save
pm2 startup

💰 RapidAPI

Votre API est prête pour RapidAPI !

Configuration pour RapidAPI

L'API est déjà configurée avec :

  • ✅ Rate limiting (général + recherche + téléchargement)
  • ✅ Format de réponse standardisé {success, data}
  • X-Request-ID sur toutes les réponses
  • ✅ Documentation Swagger interactive (/api-docs)
  • ✅ Spec OpenAPI 3.0 (openapi.json) prête à importer
  • ✅ Collection Postman 2.1 incluse
  • ✅ Gestion d'erreurs cohérente
  • ✅ Headers CORS configurables via CORS_ORIGINS

Importer la spec OpenAPI sur RapidAPI

Le fichier openapi.json est à la racine du projet (28 endpoints documentés, operationId sur chaque opération).

  1. Déployer l'API sur un serveur public (Vercel recommandé)
  2. Mettre à jour servers[0].url dans openapi.json avec votre domaine de production
  3. Sur RapidAPI Provider Hub → "Add New API" → importer openapi.json

Plans Tarifaires Suggérés

PlanRequêtes/moisPrixRevenu (100 clients)
FREE3,000Gratuit0€
BASIC10,000$9.99$999
PRO100,000$49.99$4,999
ULTRA1,000,000$199.99$19,999

Collection Postman

Trois fichiers inclus à la racine :

FichierDescription
YouTube_API_Full.postman_collection.jsonCollection 2.1 — 7 dossiers, 32 requêtes
YouTube_API_Local.postman_environment.jsonEnvironnement local (http://localhost:3000)
YouTube_API_Production.postman_environment.jsonEnvironnement production (à configurer)

Import : Postman → Import → sélectionner les 3 fichiers → choisir l'environnement souhaité.


🐛 Dépannage

Erreur : "Port already in use"

Solution : Changez le port dans .env

PORT=3001

Erreur : "Clé API YouTube non configurée"

Solution : Vérifiez votre .env

cat .env | grep YOUTUBE_API_KEY
# Doit afficher : YOUTUBE_API_KEY=votre_clé

Erreur 403 : "Quota API dépassé"

Solutions :

  1. Attendez 24h pour le reset
  2. Utilisez le cache (réduit de 80% les appels)
  3. Demandez une augmentation de quota sur Google Cloud Console

Erreur : "Cannot find module"

Solution :

rm -rf node_modules package-lock.json
npm install

Cache ne fonctionne pas

Vérification :

$curl http://localhost:3000/admin/cache/stats

Solution : Redémarrez le serveur

$npm start

Logs ne s'écrivent pas

Solution :

mkdir -p logs
npm start

Erreur 429 : "Too Many Requests"

Solution : Rate limit dépassé

  • Attendez quelques minutes
  • Ou augmentez les limites dans .env :
RATE_LIMIT_MAX_REQUESTS=200

Erreur : "Could not extract functions" (Téléchargement)

Cause : YouTube change régulièrement ses protections

Solution : L'API utilise maintenant @distube/ytdl-core qui est plus robuste

  • Si le problème persiste, réinstallez :
$npm install
  • Ou ajoutez un cookie YouTube dans .env :
YT_COOKIE=votre_cookie_youtube

Problème de CORS

Solution : Configurer la variable d'environnement dans .env

CORS_ORIGINS=https://votre-app.com,https://autre-domaine.com

En développement, laisser CORS_ORIGINS vide autorise toutes les origines.

Diagnostic Complet

# 1. Health check
curl http://localhost:3000/health
# 2. Cache
curl http://localhost:3000/admin/cache/stats
# 3. Test endpoint
curl "http://localhost:3000/api/search/videos?query=test&maxResults=1"
# 4. Logs
cat logs/error.log
# 5. Variables
cat .env | grep YOUTUBE_API_KEY

⚡ Performance

Cache Intelligent

  • TTL : 1 heure par défaut (configurable)
  • Taux de hit : ~80%
  • Réduction appels API : -80%

Statistiques :

$curl http://localhost:3000/admin/cache/stats

Vider le cache :

# Tout le cache
curl -X POST http://localhost:3000/admin/cache/clear
# Pattern spécifique
curl -X POST "http://localhost:3000/admin/cache/clear?pattern=youtube:search"

Optimisations Incluses

  • ✅ Compression gzip/brotli
  • ✅ Keep-alive HTTP
  • ✅ Connexions réutilisées
  • ✅ Timeouts optimisés
  • ✅ Code DRY (pas de duplication)

Rate Limiting

TypeLimiteFenêtre
Général100 req15 min
Téléchargement10 req15 min
Recherche30 req1 min

Headers de réponse :

X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1609459200

Monitoring

Health Check :

{
"success": true,
"status": "healthy",
"uptime": 12345,
"memory": {
"used": 45,
"total": 128,
"unit": "MB"
}
}

Logs :

  • logs/combined.log - Tous les logs
  • logs/error.log - Erreurs uniquement
  • logs/access.log - Logs HTTP

🔒 Sécurité

Mesures de Sécurité

  • Helmet.js : Headers HTTP sécurisés
  • Rate limiting : Protection contre les abus
  • Validation Joi : Validation stricte des entrées
  • CORS : Origines contrôlées
  • Secrets : Variables d'environnement uniquement
  • 0 vulnérabilité : Dépendances à jour

Bonnes Pratiques

  1. Ne jamais commiter .env
  2. Utiliser HTTPS en production
  3. Surveiller les logs d'erreur
  4. Mettre à jour régulièrement :
npm audit
npm audit fix
npm update
  1. Backup de configuration

📊 Architecture

Structure du Projet

youtube-api-full/
├── src/
│ ├── config/ # Configuration centralisée
│ │ ├── config.js
│ │ ├── logger.js # Winston
│ │ └── swagger.js # Documentation
│ ├── middleware/
│ │ ├── errorHandler.js
│ │ ├── rateLimiter.js
│ │ └── validator.js
│ ├── services/
│ │ └── youtubeService.js
│ ├── routes/
│ │ └── youtubeRoutes.js
│ └── utils/
│ └── cache.js
├── __tests__/
│ └── youtubeService.test.js
├── logs/
├── .env # À créer
├── ENV_TEMPLATE.txt # Template
├── openapi.json # Spec OpenAPI 3.0 (28 endpoints)
├── YouTube_API_Full.postman_collection.json # Collection Postman 2.1
├── YouTube_API_Local.postman_environment.json # Env local
├── YouTube_API_Production.postman_environment.json # Env production
├── package.json
├── server.js
├── vercel.json
├── Dockerfile
└── docker-compose.yml

Technologies

  • Framework : Express.js
  • Validation : Joi
  • Cache : node-cache
  • Logging : Winston
  • Documentation : Swagger/OpenAPI
  • Tests : Jest
  • Sécurité : Helmet, express-rate-limit
  • API YouTube : @distube/ytdl-core + YouTube Data API v3

🧪 Tests

# Lancer les tests
npm test
# Avec coverage
npm test -- --coverage
# Mode watch
npm test -- --watch

📝 Scripts NPM

ScriptDescription
npm startDémarrer en production
npm run devMode développement (auto-reload)
npm testLancer les tests
npm run lintVérifier le code
npm run lint:fixCorriger automatiquement

🤝 Contribution

Les contributions sont bienvenues !

  1. Fork le projet
  2. Créez une branche (git checkout -b feature/AmazingFeature)
  3. Commit (git commit -m 'Add AmazingFeature')
  4. Push (git push origin feature/AmazingFeature)
  5. Ouvrez une Pull Request

📄 Licence

MIT © 2024


🆘 Support


🎯 Roadmap

  • Authentification OAuth2
  • Webhooks pour notifications
  • Support GraphQL
  • Interface d'administration
  • Analytics avancés
  • Support multi-langues
  • WebSockets en temps réel
  • Queue system (Bull)

✅ Checklist de Démarrage

  • Node.js >= 16 installé
  • Dépendances installées (npm install)
  • Fichier .env créé
  • Clé API YouTube ajoutée
  • Serveur démarré (npm start)
  • Health check OK (curl http://localhost:3000/health)
  • Documentation accessible (http://localhost:3000/api-docs)
  • Premier endpoint testé

Fait avec ❤️ pour la communauté YouTube

YouTube API Full v2.0 - API Professionnelle, Sécurisée et Performante