Files
ScommettiApp/backend-node/API_DOCUMENTATION.md
T
2026-03-26 22:46:03 +01:00

432 lines
9.2 KiB
Markdown

# API Documentation - Amici Scommesse
## 📚 Overview
Documentazione completa dell'API Amici Scommesse v1.1.0.
**Base URL**: `http://localhost:3000/api/v1`
## 🔗 Specifica OpenAPI
La specifica OpenAPI completa è disponibile nel file `openapi.yaml`.
### Visualizzare la Specifica
**Opzione 1: Swagger UI Online**
1. Vai su https://editor.swagger.io/
2. File → Import File → Seleziona `openapi.yaml`
3. Visualizza la documentazione interattiva
**Opzione 2: Swagger UI Locale**
```bash
npx swagger-ui-watcher openapi.yaml
```
**Opzione 3: Redoc**
```bash
npx @redocly/cli preview-docs openapi.yaml
```
### Generare Client SDK
**TypeScript/JavaScript:**
```bash
npx @openapitools/openapi-generator-cli generate \
-i openapi.yaml \
-g typescript-axios \
-o ./frontend/src/api
```
**Python:**
```bash
openapi-generator-cli generate \
-i openapi.yaml \
-g python \
-o ./python-client
```
## 🌐 Endpoints API v1
### 🎯 Groups
| Metodo | Endpoint | Descrizione |
|--------|----------|-------------|
| GET | `/groups` | Lista tutti i gruppi |
| GET | `/groups/:id` | Dettaglio gruppo |
| POST | `/groups` | Crea gruppo |
| PUT | `/groups/:id` | Aggiorna gruppo |
| DELETE | `/groups/:id` | Elimina gruppo |
| PUT | `/groups/:id/members` | Aggiungi membri |
| DELETE | `/groups/:id/members/:userId` | Rimuovi membro |
### 🎲 Bets
| Metodo | Endpoint | Descrizione |
|--------|----------|-------------|
| GET | `/bets` | Lista tutte le scommesse |
| GET | `/bets/:id` | Dettaglio scommessa |
| POST | `/bets` | Crea scommessa |
| PUT | `/bets/:id` | Aggiorna scommessa |
| DELETE | `/bets/:id` | Elimina scommessa |
### 👥 Friend Requests
| Metodo | Endpoint | Descrizione |
|--------|----------|-------------|
| GET | `/friend-requests` | Lista amici |
| GET | `/friend-requests/pending` | Richieste pending |
| POST | `/friend-requests` | Invia richiesta |
| POST | `/friend-requests/:id/accept` | Accetta richiesta |
| DELETE | `/friend-requests/:id` | Rifiuta richiesta |
### 👤 Users
| Metodo | Endpoint | Descrizione |
|--------|----------|-------------|
| PUT | `/users/current` | Aggiorna profilo |
### 📦 Initial Data
| Metodo | Endpoint | Descrizione |
|--------|----------|-------------|
| GET | `/initial-data` | Carica dati iniziali |
### ❤️ Health
| Metodo | Endpoint | Descrizione |
|--------|----------|-------------|
| GET | `/health` | Health check database |
## 📝 Formato Risposte
### Successo (2xx)
```json
{
"success": true,
"message": "Operation successful",
"data": { ... },
"timestamp": "2024-01-01T00:00:00.000Z"
}
```
### Errore (4xx, 5xx)
```json
{
"success": false,
"message": "Error message",
"errors": [
{
"field": "name",
"message": "Name is required"
}
],
"timestamp": "2024-01-01T00:00:00.000Z"
}
```
## 🔐 Autenticazione
**Attuale**: Mock authentication (Mario Rossi hardcoded)
**Prossimo**: JWT authentication da implementare
## 🧪 Esempi di Chiamate
### Creare un Gruppo
```bash
curl -X POST http://localhost:3000/api/v1/groups \
-H "Content-Type: application/json" \
-d '{
"name": "Gruppo Calcio",
"members": [1, 2, 3]
}'
```
Risposta:
```json
{
"success": true,
"message": "Group created successfully",
"data": {
"id": 1,
"name": "Gruppo Calcio",
"members": [
{
"id": 1,
"name": "Mario Rossi",
"email": "mario.rossi@example.com",
"avatarUrl": null,
"score": 0
}
]
},
"timestamp": "2024-01-01T12:00:00.000Z"
}
```
### Creare una Scommessa
```bash
curl -X POST http://localhost:3000/api/v1/bets \
-H "Content-Type: application/json" \
-d '{
"title": "Chi vince il campionato?",
"description": "Scommessa sul vincitore del campionato 2024",
"stake": "50 euro",
"participants": [
{
"user": 1,
"role": "PARTICIPANT"
},
{
"user": 2,
"role": "PARTICIPANT"
}
],
"isPublic": false,
"groupId": "1"
}'
```
### Inviare Richiesta di Amicizia
```bash
curl -X POST http://localhost:3000/api/v1/friend-requests \
-H "Content-Type: application/json" \
-d '{
"identifier": 2
}'
```
oppure con email:
```bash
curl -X POST http://localhost:3000/api/v1/friend-requests \
-H "Content-Type: application/json" \
-d '{
"identifier": "luigi.verdi@example.com"
}'
```
### Aggiornare Profilo Utente
```bash
curl -X PUT http://localhost:3000/api/v1/users/current \
-H "Content-Type: application/json" \
-d '{
"name": "Mario Rossi",
"email": "mario.rossi.new@example.com",
"avatarUrl": "https://example.com/avatar.jpg"
}'
```
### Caricare Dati Iniziali
```bash
curl http://localhost:3000/api/v1/initial-data
```
### Health Check
```bash
curl http://localhost:3000/health
```
Risposta:
```json
{
"status": "healthy",
"timestamp": "2024-01-01T12:00:00.000Z",
"services": {
"postgres": "connected",
"mongodb": "connected"
}
}
```
## 🔄 Migrazione da API Legacy
### API Legacy (Backward Compatibility)
Le vecchie route sono ancora disponibili su `/api/legacy/*` per compatibilità:
```
/api/legacy/groups → legacy format
/api/legacy/bets → legacy format
/api/legacy/friend-requests → legacy format
```
### Differenze tra v1 e Legacy
| Aspetto | Legacy | v1 |
|---------|--------|-----|
| Formato risposta | Varia | Standardizzato |
| Validazione | Inline | Joi schema |
| Error handling | Inconsistente | Centralizzato |
| Success status | Varia | Sempre con wrapper |
| Timestamp | No | Sì |
### Piano di Migrazione Frontend
1. **Fase 1**: Testare endpoint v1 in sviluppo
2. **Fase 2**: Migrare chiamate API da `/api/*` a `/api/v1/*`
3. **Fase 3**: Aggiornare gestione risposte (nuovo formato)
4. **Fase 4**: Gestire nuovi errori standardizzati
5. **Fase 5**: Deprecare chiamate legacy
## 📊 Codici di Stato HTTP
| Codice | Significato | Quando |
|--------|-------------|--------|
| 200 | OK | Operazione riuscita |
| 201 | Created | Risorsa creata |
| 400 | Bad Request | Validation error |
| 404 | Not Found | Risorsa non trovata |
| 409 | Conflict | Conflitto (es: già amici) |
| 500 | Internal Error | Errore server |
| 503 | Service Unavailable | Database non disponibile |
## 🛠️ Testing con Postman
### Importare Specifica OpenAPI
1. Apri Postman
2. Import → Link → Incolla URL o File
3. Seleziona `openapi.yaml`
4. Postman genera automaticamente la collection
### Environment Variables
Crea un environment Postman con:
```json
{
"baseUrl": "http://localhost:3000/api/v1",
"legacyUrl": "http://localhost:3000/api/legacy"
}
```
## 🚀 Integrare con Frontend
### Axios Example (TypeScript)
```typescript
import axios from 'axios';
const api = axios.create({
baseURL: 'http://localhost:3000/api/v1',
headers: {
'Content-Type': 'application/json',
},
});
// Response Interceptor per formato standardizzato
api.interceptors.response.use(
(response) => response.data, // Ritorna solo { success, message, data, timestamp }
(error) => {
if (error.response) {
// Server ha risposto con errore
return Promise.reject(error.response.data);
}
return Promise.reject(error);
}
);
// Esempio uso
async function createGroup(name: string, members: number[]) {
try {
const response = await api.post('/groups', { name, members });
console.log('Success:', response.data);
return response.data;
} catch (error) {
console.error('Error:', error.message, error.errors);
throw error;
}
}
```
### Fetch Example (JavaScript)
```javascript
async function createGroup(name, members) {
const response = await fetch('http://localhost:3000/api/v1/groups', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ name, members }),
});
const result = await response.json();
if (!result.success) {
throw new Error(result.message);
}
return result.data;
}
```
### React Hook Example
```typescript
import { useState, useEffect } from 'react';
import api from './api';
function useGroups() {
const [groups, setGroups] = useState([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
useEffect(() => {
async function fetchGroups() {
setLoading(true);
try {
const response = await api.get('/groups');
setGroups(response.data);
} catch (err) {
setError(err);
} finally {
setLoading(false);
}
}
fetchGroups();
}, []);
return { groups, loading, error };
}
```
## 🐛 Troubleshooting
### Errore 404 su endpoint v1
Verifica che il server sia avviato e che stai usando `/api/v1/` e non `/api/`.
### Validation errors
Controlla la specifica OpenAPI per i campi required e i formati accettati.
### CORS errors
Il server ha CORS abilitato. Se riscontri problemi, verifica la configurazione del frontend.
### Health check fallisce
Verifica che PostgreSQL e MongoDB siano in esecuzione e accessibili.
## 📞 Supporto
Per problemi o domande:
- Consulta la specifica OpenAPI completa in `openapi.yaml`
- Vedi esempi in `IMPLEMENTATION_GUIDE.md`
- Controlla il CHANGELOG.md per ultime modifiche
## 🔗 Link Utili
- [Swagger Editor](https://editor.swagger.io/)
- [OpenAPI Generator](https://openapi-generator.tech/)
- [Postman](https://www.postman.com/)
- [Redoc](https://redocly.com/redoc/)