Guide de Consommation de l'API MyTelevision
Guide complet des bonnes pratiques pour consommer l'API MyTelevision de maniere efficace et professionnelle.
Informations cles
| Element | Detail |
|---|---|
| Base URL Dev | http://localhost:3000/api/v2 |
| Base URL Staging | https://staging-api.mytelevision.app/api/v2 |
| Base URL Prod | https://api.mytelevision.app/api/v2 |
| Documentation | http://localhost:3000/api/docs |
| Authentification | JWT Bearer Token |
| Format | JSON (application/json) |
| Versioning | URL-based (/api/v2) |
1. Outils de test et consommation d'API
1.1 Postman
Structure de collection recommandee
MyTelevision API v2
+-- Auth
| +-- POST Register
| +-- POST Login
| +-- POST Refresh Token
| +-- GET Current User
| +-- POST Logout
+-- Movies
| +-- GET List Movies (Paginated)
| +-- GET Movie by ID
| +-- GET Featured Movies
| +-- GET Search Movies
+-- Series
| +-- GET List Series
| +-- GET Series by ID
| +-- GET Season Episodes
+-- Live TV
| +-- GET Live Channels
| +-- GET Channel by ID
+-- Admin
| +-- Movies (CRUD)
| +-- Series (CRUD)
| +-- Users (Management)
+-- Utilities
+-- GET Health Check
+-- GET Settings
Variables d'environnement
Creez trois environnements dans Postman : Development, Staging, Production
Environment: Development
{
"baseUrl": "http://localhost:3000/api/v2",
"accessToken": "",
"refreshToken": "",
"userId": "",
"docsUrl": "http://localhost:3000/api/docs"
}
Environment: Staging
{
"baseUrl": "https://staging-api.mytelevision.app/api/v2",
"accessToken": "",
"refreshToken": "",
"userId": "",
"docsUrl": "https://staging-api.mytelevision.app/api/docs"
}
Environment: Production
{
"baseUrl": "https://api.mytelevision.app/api/v2",
"accessToken": "",
"refreshToken": "",
"userId": "",
"docsUrl": "https://api.mytelevision.app/api/docs"
}
Pre-request scripts pour auto-refresh token
// Pre-request Script - Collection Level
// Auto-refresh token if expired
const moment = require('moment');
const accessToken = pm.environment.get('accessToken');
const tokenExpiry = pm.environment.get('tokenExpiry');
if (accessToken && tokenExpiry) {
const now = moment();
const expiry = moment(tokenExpiry);
if (expiry.diff(now, 'minutes') < 5) {
console.log('Token expiring soon, refreshing...');
const refreshToken = pm.environment.get('refreshToken');
const baseUrl = pm.environment.get('baseUrl');
pm.sendRequest(
{
url: `${baseUrl}/auth/refresh`,
method: 'POST',
header: { 'Content-Type': 'application/json' },
body: {
mode: 'raw',
raw: JSON.stringify({ refreshToken: refreshToken }),
},
},
(err, response) => {
if (err) {
console.error('Token refresh failed:', err);
} else {
const jsonData = response.json();
pm.environment.set('accessToken', jsonData.accessToken);
pm.environment.set('refreshToken', jsonData.refreshToken);
const newExpiry = moment().add(15, 'minutes').toISOString();
pm.environment.set('tokenExpiry', newExpiry);
console.log('Token refreshed successfully');
}
},
);
}
}
Tests automatises dans Postman
// Test GET /movies
pm.test('Status code is 200', function () {
pm.response.to.have.status(200);
});
pm.test('Response time is less than 500ms', function () {
pm.expect(pm.response.responseTime).to.be.below(500);
});
pm.test('Response has pagination structure', function () {
var jsonData = pm.response.json();
pm.expect(jsonData).to.have.property('data');
pm.expect(jsonData).to.have.property('meta');
pm.expect(jsonData.meta).to.have.property('total');
pm.expect(jsonData.meta).to.have.property('page');
pm.expect(jsonData.meta).to.have.property('limit');
pm.expect(jsonData.meta).to.have.property('totalPages');
});
Import via CLI (Newman)
npm install -g newman
newman run postman/MyTelevision-API-v2.postman_collection.json \
-e postman/Development.postman_environment.json \
--reporters cli,json \
--reporter-json-export results.json
1.2 Insomnia
- Interface plus legere que Postman
- Git-friendly (fichiers YAML/JSON)
- Excellent support GraphQL
- Open source
Import depuis Swagger/OpenAPI
1. Create > Import From > URL
2. Entrer: http://localhost:3000/api/docs-json
3. Toutes les routes seront importees automatiquement
1.3 cURL
Login et sauvegarde du token
TOKEN=$(curl -s -X POST http://localhost:3000/api/v2/auth/login \
-H "Content-Type: application/json" \
-d '{
"email": "[email protected]",
"password": "SecurePass123"
}' | jq -r '.tokens.accessToken')
echo "Token: $TOKEN"
Requete authentifiee
curl -X GET http://localhost:3000/api/v2/movies \
-H "Authorization: Bearer $TOKEN" \
-H "Accept: application/json" | jq '.'
Pagination avancee
BASE_URL="http://localhost:3000/api/v2"
PAGE=1
TOTAL_PAGES=1
while [ $PAGE -le $TOTAL_PAGES ]; do
echo "Fetching page $PAGE..."
RESPONSE=$(curl -s -X GET "$BASE_URL/movies?page=$PAGE&limit=20" \
-H "Authorization: Bearer $TOKEN")
if [ $PAGE -eq 1 ]; then
TOTAL_PAGES=$(echo $RESPONSE | jq -r '.meta.totalPages')
echo "Total pages: $TOTAL_PAGES"
fi
echo $RESPONSE | jq '.data[] | {id, title}' >> movies.json
PAGE=$((PAGE + 1))
done
2. Integration dans la CI/CD
2.1 Tests de contrat OpenAPI
name: API Contract Tests
on:
pull_request:
branches: [main, develop]
jobs:
contract-validation:
name: Validate OpenAPI Schema
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '18'
- name: Install dependencies
run: npm ci
- name: Generate OpenAPI spec
run: |
npm run start:prod &
sleep 10
curl http://localhost:3000/api/docs-json > openapi.json
- name: Validate OpenAPI spec
uses: char0n/swagger-editor-validate@v1
with:
definition-file: openapi.json
2.2 Secrets GitHub
# Required Secrets (Settings > Secrets and variables > Actions)
JWT_SECRET: 'your-super-secret-jwt-key-min-32-chars'
JWT_REFRESH_SECRET: 'your-super-secret-refresh-key-32-chars'
TMDB_API_KEY: 'your-tmdb-api-key'
R2_ACCESS_KEY_ID: 'your-r2-access-key'
R2_SECRET_ACCESS_KEY: 'your-r2-secret-key'
3. Patterns et conventions
3.1 Pagination standardisee
Toutes les listes paginees utilisent le meme format de reponse :
{
"data": [...],
"meta": {
"total": 150,
"page": 1,
"limit": 20,
"totalPages": 8,
"hasNextPage": true,
"hasPreviousPage": false
}
}
3.2 Format d'erreur standardise
{
"statusCode": 400,
"message": "Validation failed",
"error": "Bad Request",
"details": [
{
"field": "email",
"message": "email must be a valid email address"
}
]
}
3.3 Codes de statut HTTP
| Code | Description |
|---|---|
| 200 | Succes |
| 201 | Cree avec succes |
| 204 | Succes sans contenu |
| 400 | Requete invalide |
| 401 | Non authentifie |
| 403 | Interdit (permission insuffisante) |
| 404 | Ressource non trouvee |
| 409 | Conflit |
| 422 | Entite non traitable |
| 429 | Trop de requetes (rate limit) |
| 500 | Erreur serveur |
3.4 Internationalisation (i18n)
L'API supporte la localisation via :
- Query Parameter :
?lang=en_US(priorite la plus haute) - Accept-Language Header :
Accept-Language: en-US,en;q=0.9,fr;q=0.8 - Par defaut :
fr_FR
4. Optimisation et performance
4.1 Mise en cache
- Les reponses GET sont cachees cote serveur (Redis, TTL 5 minutes)
- Respectez les headers
Cache-Controldans les reponses - Implementez un cache local cote client pour les donnees statiques
4.2 Rate Limiting
| Tier | Limite | Fenetre |
|---|---|---|
| Short | 3 requetes | 1 seconde |
| Medium | 20 requetes | 10 secondes |
| Long | 100 requetes | 1 minute |
Les headers de reponse incluent :
X-RateLimit-Limit: Limite de requetesX-RateLimit-Remaining: Requetes restantesX-RateLimit-Reset: Timestamp de reinitialisation
4.3 Compression
- L'API supporte gzip/deflate (
Accept-Encoding: gzip) - Activez la compression dans vos clients HTTP
5. Checklist developpeur
Avant d'integrer l'API
- Lire la documentation Swagger (
/api/docs) - Configurer les variables d'environnement
- Tester l'endpoint de sante (
GET /health) - Implementer le flux d'authentification
- Mettre en place l'auto-refresh des tokens
- Gerer les codes d'erreur courants (401, 403, 429)
Bonnes pratiques
- Toujours envoyer
Content-Type: application/json - Implementer la pagination pour les listes
- Gerer le rate limiting avec retry et backoff
- Utiliser HTTPS en staging et production
- Ne jamais exposer les tokens dans les logs
- Implementer la gestion des erreurs reseau
6. Ressources et outils recommandes
| Ressource | Description |
|---|---|
| Swagger UI | http://localhost:3000/api/docs |
| Postman Collections | postman/ dans le projet |
| Newman | CLI pour Postman |
| jq | Parseur JSON en ligne de commande |
| HTTPie | Alternative a cURL plus conviviale |
| ngrok | Tunnel pour tester les webhooks localement |
Pour aller plus loin
Consultez le Guide Complet - Partie I pour une documentation exhaustive sur la consommation de l'API, incluant des exemples avances de Postman, Insomnia et cURL.