YouTube API Full
Pricing
from $10.00 / 1,000 api requests
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
Maintained by CommunityActor stats
0
Bookmarked
1
Total users
0
Monthly active users
44 minutes ago
Last modified
Categories
Share
🎥 YouTube API Full v2.0
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
- Configuration
- Utilisation
- API Endpoints
- Exemples de Code
- Déploiement
- RapidAPI
- Dépannage
- Performance
🚀 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épendancesnpm install# 2. Configurercp ENV_TEMPLATE.txt .env# Éditer .env et ajouter votre YOUTUBE_API_KEY# 3. Démarrernpm 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 :
# ServeurNODE_ENV=productionPORT=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 productionCORS_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_cookieYT_TOKEN=votre_tokenYT_LANG=en # Langue ytdl (défaut: en)# Cache (en secondes)CACHE_TTL=3600CACHE_CHECK_PERIOD=600# Rate LimitingRATE_LIMIT_WINDOW_MS=900000RATE_LIMIT_MAX_REQUESTS=100# LoggingLOG_LEVEL=info
Obtenir une Clé API YouTube
- Allez sur Google Cloud Console
- Créez un projet
- Activez "YouTube Data API v3"
- Créez une clé API dans "Identifiants"
- Copiez la clé dans votre
.env
💻 Utilisation
Démarrage
# Mode productionnpm start# Mode développement (auto-reload)npm run dev# Testsnpm test# Lintingnpm run lintnpm run lint:fix
Vérification
# Health checkcurl 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/statscurl -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
| Endpoint | Méthode | Description |
|---|---|---|
/api/search/videos | GET | Rechercher des vidéos (filtres durée, définition, ordre) |
/api/search/channels | GET | Rechercher des chaînes |
/api/search/playlists | GET | Rechercher des playlists |
/api/search/movies | GET | Rechercher des films |
/api/search/episodes | GET | Rechercher des épisodes TV |
/api/search/all | GET | Recherche combinée vidéos + chaînes + playlists |
/api/hashtag | GET | Recherche 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 suivantecurl "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®ionCode=FR"
📺 Vidéos
| Endpoint | Méthode | Description |
|---|---|---|
/api/videos | GET | Détails complets (id, part) |
/api/videoStats | GET | Statistiques (vues, likes, commentaires) |
/api/videoStatus | GET | Statut upload et confidentialité |
/api/videoPlayer | GET | Code embed iframe |
/api/videoTopics | GET | Topics Freebase |
/api/videoCategories | GET | Catégories par région |
/api/captions | GET | Pistes de sous-titres |
/api/trending | GET | Vidé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 Francecurl "http://localhost:3000/api/videoCategories?regionCode=FR&hl=fr"# Sous-titres d'une vidéocurl "http://localhost:3000/api/captions?videoId=dQw4w9WgXcQ"
📢 Chaînes
| Endpoint | Méthode | Description |
|---|---|---|
/api/channelsByIds | GET | Infos par ID(s), virgule pour plusieurs |
/api/channelByUsername | GET | Infos par handle (@username) |
/api/channelSections | GET | Sections de la page chaîne |
/api/channelSectionsById | GET | Section spécifique par ID |
/api/activities | GET | Fil d'activités de la chaîne |
/api/subscriptions | GET | Abonnements de la chaîne |
💬 Commentaires
| Endpoint | Méthode | Description |
|---|---|---|
/api/comments | GET | Fils de commentaires d'une vidéo |
/api/commentReplies | GET | Réponses à un commentaire |
/api/comment | GET | Commentaire spécifique par ID |
📋 Playlists
| Endpoint | Méthode | Description |
|---|---|---|
/api/playlists | GET | Playlists d'une chaîne |
/api/playlistCode | GET | Code embed iframe des playlists |
/api/playlistItems | GET | Vidéos contenues dans une playlist |
Exemple :
$curl "http://localhost:3000/api/playlistItems?playlistId=PLxxxxxx&maxResults=50"
💾 Téléchargement
| Endpoint | Méthode | Description |
|---|---|---|
/api/download | POST | Métadonnées + URLs de streaming directes |
Body parameters :
| Paramètre | Requis | Description |
|---|---|---|
url | ✅ | URL YouTube complète |
cookie | ❌ | Cookie de session YouTube (pour contenu restreint) |
poToken | ❌ | Proof of Origin Token YouTube |
visitorData | ❌ | Visitor 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/downloadretourneraSign in to confirm you're not a botmême avec des cookies valides, car lepoTokendoit être généré depuis la même IP résidentielle que celle effectuant la requête.Contournement : passer
cookie,poTokenetvisitorDatadirectement dans le body, obtenus depuis un navigateur sur IP résidentielle (DevTools > Network > requêteyoutubei.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
| Endpoint | Méthode | Description |
|---|---|---|
/health | GET | Health check |
/admin/cache/stats | GET | Stats cache (header x-admin-key requis si ADMIN_API_KEY configuré) |
/admin/cache/clear | POST | Vider 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 recherchecurl -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éosasync function searchVideos(query) {const response = await axios.get(`${BASE_URL}/search/videos`, {params: { query, maxResults: 10 }});return response.data;}// Télécharger une vidéoasync function downloadVideo(url) {const response = await axios.post(`${BASE_URL}/download`, { url });return response.data;}// Statistiques vidéoasync function getVideoStats(videoId) {const response = await axios.get(`${BASE_URL}/videoStats`, {params: { id: videoId }});return response.data;}// UtilisationsearchVideos('nodejs tutorial').then(data => console.log(data));
Python
import requestsBASE_URL = 'http://localhost:3000/api'# Rechercher des vidéosdef 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éodef download_video(url):response = requests.post(f'{BASE_URL}/download',json={'url': url})return response.json()# Statistiquesdef get_video_stats(video_id):response = requests.get(f'{BASE_URL}/videoStats',params={'id': video_id})return response.json()# Utilisationvideos = search_videos('python programming')print(videos)
PHP
<?php$baseUrl = 'http://localhost:3000/api';// Rechercher des vidéosfunction 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
# Recherchercurl "http://localhost:3000/api/search/videos?query=javascript&maxResults=5"# Téléchargercurl -X POST http://localhost:3000/api/download \-H "Content-Type: application/json" \-d '{"url": "https://www.youtube.com/watch?v=VIDEO_ID"}'# Statistiquescurl "http://localhost:3000/api/videoStats?id=VIDEO_ID"# Tendancescurl "http://localhost:3000/api/trending?geo=FR"
🐳 Déploiement
Docker
# Builddocker build -t youtube-api .# Rundocker run -p 3000:3000 --env-file .env youtube-api# Ou avec Docker Composedocker-compose up -d
Heroku
# Créer l'appheroku create youtube-api-votre-nom# Configurerheroku config:set YOUTUBE_API_KEY=votre_cléheroku config:set NODE_ENV=production# Déployergit push heroku main# Voir les logsheroku logs --tail
Vercel
# Installer Vercel CLInpm i -g vercel# Déployervercel --prod# Configurer les variablesvercel env add YOUTUBE_API_KEYvercel env add NODE_ENV
DigitalOcean / AWS / GCP
Utilisez Docker ou déployez directement avec Node.js :
# Sur votre serveurgit clone <votre-repo>cd youtube-api-fullnpm install --productioncp ENV_TEMPLATE.txt .env# Éditer .env# Avec PM2 (recommandé)npm install -g pm2pm2 start server.js --name youtube-apipm2 savepm2 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-IDsur 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).
- Déployer l'API sur un serveur public (Vercel recommandé)
- Mettre à jour
servers[0].urldansopenapi.jsonavec votre domaine de production - Sur RapidAPI Provider Hub → "Add New API" → importer
openapi.json
Plans Tarifaires Suggérés
| Plan | Requêtes/mois | Prix | Revenu (100 clients) |
|---|---|---|---|
| FREE | 3,000 | Gratuit | 0€ |
| BASIC | 10,000 | $9.99 | $999 |
| PRO | 100,000 | $49.99 | $4,999 |
| ULTRA | 1,000,000 | $199.99 | $19,999 |
Collection Postman
Trois fichiers inclus à la racine :
| Fichier | Description |
|---|---|
YouTube_API_Full.postman_collection.json | Collection 2.1 — 7 dossiers, 32 requêtes |
YouTube_API_Local.postman_environment.json | Environnement local (http://localhost:3000) |
YouTube_API_Production.postman_environment.json | Environnement 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 :
- Attendez 24h pour le reset
- Utilisez le cache (réduit de 80% les appels)
- Demandez une augmentation de quota sur Google Cloud Console
Erreur : "Cannot find module"
Solution :
rm -rf node_modules package-lock.jsonnpm 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 logsnpm 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 checkcurl http://localhost:3000/health# 2. Cachecurl http://localhost:3000/admin/cache/stats# 3. Test endpointcurl "http://localhost:3000/api/search/videos?query=test&maxResults=1"# 4. Logscat logs/error.log# 5. Variablescat .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 cachecurl -X POST http://localhost:3000/admin/cache/clear# Pattern spécifiquecurl -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
| Type | Limite | Fenêtre |
|---|---|---|
| Général | 100 req | 15 min |
| Téléchargement | 10 req | 15 min |
| Recherche | 30 req | 1 min |
Headers de réponse :
X-RateLimit-Limit: 100X-RateLimit-Remaining: 95X-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 logslogs/error.log- Erreurs uniquementlogs/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
- Ne jamais commiter
.env - Utiliser HTTPS en production
- Surveiller les logs d'erreur
- Mettre à jour régulièrement :
npm auditnpm audit fixnpm update
- 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 testsnpm test# Avec coveragenpm test -- --coverage# Mode watchnpm test -- --watch
📝 Scripts NPM
| Script | Description |
|---|---|
npm start | Démarrer en production |
npm run dev | Mode développement (auto-reload) |
npm test | Lancer les tests |
npm run lint | Vérifier le code |
npm run lint:fix | Corriger automatiquement |
🤝 Contribution
Les contributions sont bienvenues !
- Fork le projet
- Créez une branche (
git checkout -b feature/AmazingFeature) - Commit (
git commit -m 'Add AmazingFeature') - Push (
git push origin feature/AmazingFeature) - Ouvrez une Pull Request
📄 Licence
MIT © 2024
🆘 Support
- 📧 Email : support@youtubeapi.com
- 🐛 Issues : GitHub Issues
- 📚 Documentation : http://localhost:3000/api-docs
- 💬 Discussions : GitHub Discussions
🎯 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
.envcréé - 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