mcServerWebsite/app/document/GUIDE_USER_RAPIDE_API.md
2026-04-09 15:23:15 +02:00

207 lines
4.5 KiB
Markdown
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 🚀 Guide rapide API - Démarrage en 5 minutes
## 1⃣ Créer une clé API
### Via ligne de commande
```bash
php bin/console app:api-key:create votre_pseudo "Nom de votre application"
```
**Exemple:**
```bash
php bin/console app:api-key:create john "Mon App Mobile"
```
Vous recevrez un **token unique** - conservez-le en lieu sûr!
### Via l'API (pour utilisateurs connectés)
```bash
curl -X POST http://localhost:8000/api/api-keys \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{"name": "Nom de votre clé"}'
```
---
## 2⃣ Accéder à l'API
### Option A: Avec une clé API (recommandé pour applications externes)
```bash
curl -X GET http://localhost:8000/api/profile \
-H "Authorization: Bearer your_api_token_here"
```
**Exemple de réponse:**
```json
{
"id": 1,
"pseudo": "john",
"roles": ["ROLE_USER"],
"authenticatedVia": "api_key"
}
```
### Option B: Via session (pour utilisateurs connectés au site)
```bash
# Après connexion au site web
curl http://localhost:8000/api/profile
```
La session est automatiquement utilisée.
---
## 3⃣ Endpoints disponibles
| Méthode | Route | Authentification | Description |
|---------|-------|------------------|-------------|
| `GET` | `/api/health` | ❌ Non | Vérifier l'état de l'API |
| `GET` | `/api/profile` | ✅ Oui | Votre profil utilisateur |
| `GET` | `/api/api-keys` | ✅ Oui | Vos clés API / toutes (admin) |
| `POST` | `/api/api-keys` | ✅ Oui | Créer une nouvelle clé |
| `DELETE` | `/api/api-keys/{id}` | ✅ Oui | Supprimer une clé |
| `PATCH` | `/api/api-keys/{id}/deactivate` | ✅ Oui | Désactiver une clé |
---
## 4⃣ Exemples pratiques
### Vérifier l'état de l'API
```bash
curl http://localhost:8000/api/health
```
### Récupérer votre profil
```bash
curl -X GET http://localhost:8000/api/profile \
-H "Authorization: Bearer your_token"
```
### Lister vos clés API
```bash
curl -X GET http://localhost:8000/api/api-keys \
-H "Authorization: Bearer your_token"
```
### Créer une nouvelle clé
```bash
curl -X POST http://localhost:8000/api/api-keys \
-H "Authorization: Bearer your_token" \
-H "Content-Type: application/json" \
-d '{"name": "Nouvelle clé", "expiresAt": "2027-04-03T00:00:00Z"}'
```
### Supprimer une clé
```bash
curl -X DELETE http://localhost:8000/api/api-keys/1 \
-H "Authorization: Bearer your_token"
```
---
## 5⃣ Utilisation dans votre application
### JavaScript / Fetch
```javascript
const apiToken = 'your_api_token';
async function getProfile() {
const response = await fetch('http://localhost:8000/api/profile', {
headers: {
'Authorization': `Bearer ${apiToken}`
}
});
if (!response.ok) {
throw new Error(`Erreur: ${response.status}`);
}
return response.json();
}
getProfile().then(profile => console.log(profile));
```
### Python / Requests
```python
import requests
api_token = 'your_api_token'
headers = {'Authorization': f'Bearer {api_token}'}
response = requests.get('http://localhost:8000/api/profile', headers=headers)
response.raise_for_status()
print(response.json())
```
### PHP / cURL
```php
$token = 'your_api_token';
$url = 'http://localhost:8000/api/profile';
$options = [
'http' => [
'method' => 'GET',
'header' => "Authorization: Bearer $token"
]
];
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
$data = json_decode($response, true);
print_r($data);
```
---
## 6⃣ Gestion des erreurs courants
### 401 Unauthorized
- **Cause**: Token invalide ou expiré, pas d'authentification
- **Solution**: Vérifier votre token, le renouveler si nécessaire
### 403 Forbidden
- **Cause**: Authentifié mais permissions insuffisantes
- **Solution**: Vérifier que vous avez les droits nécessaires
### 404 Not Found
- **Cause**: Ressource inexistante (ex: clé API inexistante)
- **Solution**: Vérifier l'ID de la ressource
---
## 7⃣ Sécurité
**À FAIRE:**
- Garder votre token secret
- Utiliser HTTPS en production
- Créer de nouvelles clés régulièrement
- Révoquer les clés inutilisées
**À NE PAS FAIRE:**
- Partager votre token
- Mettre votre token en version control (git)
- Utiliser le même token pour tout
- Ignorer les expirations
---
## 🆘 Besoin d'aide?
Consultez la **documentation complète** dans `DOCUMENTATION_API.md` pour:
- Architecture détaillée
- Configuration avancée
- Intégration dans différents frameworks
- FAQ et dépannage
---
**Prêt à utiliser l'API!** 🎉