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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Ejemplos de uso de la API QuantumLink
|
3 |
+
Incluye cliente Python, JavaScript y curl
|
4 |
+
"""
|
5 |
+
|
6 |
+
import requests
|
7 |
+
import json
|
8 |
+
from typing import Dict, Any, List
|
9 |
+
|
10 |
+
# ==================== CLIENTE PYTHON ====================
|
11 |
+
|
12 |
+
class QuantumLinkClient:
|
13 |
+
"""Cliente Python para la API QuantumLink"""
|
14 |
+
|
15 |
+
def __init__(self, base_url: str = "http://localhost:5000", auth_token: str = None):
|
16 |
+
self.base_url = base_url.rstrip('/')
|
17 |
+
self.auth_token = auth_token
|
18 |
+
self.session = requests.Session()
|
19 |
+
|
20 |
+
if auth_token:
|
21 |
+
self.session.headers.update({
|
22 |
+
'Authorization': f'Bearer {auth_token }'
|
23 |
+
|
24 |
+
# 3. Decodificar un mensaje
|
25 |
+
curl -X POST http://localhost:5000/api/v1/decode \
|
26 |
+
-H "Content-Type: application/json" \
|
27 |
+
-H "Authorization: Bearer valid_user123" \
|
28 |
+
-d '{
|
29 |
+
"package_id": "BiMO-12345678",
|
30 |
+
"measurements": [
|
31 |
+
{"energia_medida": 5.2, "timestamp": "2025-01-01T10:00:00Z"},
|
32 |
+
{"energia_medida": 3.8, "timestamp": "2025-01-01T10:00:01Z"},
|
33 |
+
{"energia_medida": 4.1, "timestamp": "2025-01-01T10:00:02Z"}
|
34 |
+
]
|
35 |
+
}'
|
36 |
+
|
37 |
+
# 4. Obtener historial de paquetes
|
38 |
+
curl -X GET http://localhost:5000/api/v1/packages \
|
39 |
+
-H "Authorization: Bearer valid_user123"
|
40 |
+
|
41 |
+
# 5. Obtener detalles de un paquete espec铆fico
|
42 |
+
curl -X GET http://localhost:5000/api/v1/packages/BiMO-12345678 \
|
43 |
+
-H "Authorization: Bearer valid_user123"
|
44 |
+
|
45 |
+
# 6. Ejemplo de error - sin autenticaci贸n
|
46 |
+
curl -X POST http://localhost:5000/api/v1/encode \
|
47 |
+
-H "Content-Type: application/json" \
|
48 |
+
-d '{"message": "Test without auth"}'
|
49 |
+
"""
|
50 |
+
|
51 |
+
# ==================== TESTS AUTOMATIZADOS ====================
|
52 |
+
|
53 |
+
def create_test_suite():
|
54 |
+
"""Crear suite de tests automatizados con pytest"""
|
55 |
+
return '''
|
56 |
+
# test_quantumlink_api.py
|
57 |
+
import pytest
|
58 |
+
import json
|
59 |
+
from app import create_app
|
60 |
+
|
61 |
+
@pytest.fixture
|
62 |
+
def client():
|
63 |
+
"""Cliente de prueba para Flask"""
|
64 |
+
app = create_app()
|
65 |
+
app.config['TESTING'] = True
|
66 |
+
with app.test_client() as client:
|
67 |
+
yield client
|
68 |
+
|
69 |
+
@pytest.fixture
|
70 |
+
def auth_headers():
|
71 |
+
"""Headers con autenticaci贸n v谩lida"""
|
72 |
+
return {
|
73 |
+
'Authorization': 'Bearer valid_test_user',
|
74 |
+
'Content-Type': 'application/json'
|
75 |
+
}
|
76 |
+
|
77 |
+
class TestHealthCheck:
|
78 |
+
"""Tests para el endpoint de health check"""
|
79 |
+
|
80 |
+
def test_health_check(self, client):
|
81 |
+
"""Test b谩sico de health check"""
|
82 |
+
response = client.get('/')
|
83 |
+
assert response.status_code == 200
|
84 |
+
data = json.loads(response.data)
|
85 |
+
assert data['status'] == 'success'
|
86 |
+
assert 'QuantumLink API' in data['message']
|
87 |
+
|
88 |
+
class TestAuthentication:
|
89 |
+
"""Tests para autenticaci贸n"""
|
90 |
+
|
91 |
+
def test_encode_without_auth(self, client):
|
92 |
+
"""Test de codificaci贸n sin autenticaci贸n"""
|
93 |
+
response = client.post('/api/v1/encode',
|
94 |
+
json={'message': 'test'},
|
95 |
+
content_type='application/json')
|
96 |
+
assert response.status_code == 401
|
97 |
+
data = json.loads(response.data)
|
98 |
+
assert data['code'] == 'UNAUTHORIZED'
|
99 |
+
|
100 |
+
def test_encode_with_invalid_token(self, client):
|
101 |
+
"""Test con token inv谩lido"""
|
102 |
+
headers = {'Authorization': 'Bearer invalid_token'}
|
103 |
+
response = client.post('/api/v1/encode',
|
104 |
+
json={'message': 'test'},
|
105 |
+
headers=headers)
|
106 |
+
assert response.status_code == 401
|
107 |
+
data = json.loads(response.data)
|
108 |
+
assert data['code'] == 'INVALID_TOKEN'
|
109 |
+
|
110 |
+
class TestEncoding:
|
111 |
+
"""Tests para codificaci贸n de mensajes"""
|
112 |
+
|
113 |
+
def test_encode_valid_message(self, client, auth_headers):
|
114 |
+
"""Test de codificaci贸n exitosa"""
|
115 |
+
message_data = {
|
116 |
+
'message': 'QUANTUM TEST MESSAGE',
|
117 |
+
'options': {
|
118 |
+
'encoding_type': 'BiMO',
|
119 |
+
'priority': 'high'
|
120 |
+
}
|
121 |
+
}
|
122 |
+
response = client.post('/api/v1/encode',
|
123 |
+
json=message_data,
|
124 |
+
headers=auth_headers)
|
125 |
+
assert response.status_code == 201
|
126 |
+
data = json.loads(response.data)
|
127 |
+
assert data['status'] == 'success'
|
128 |
+
assert 'package_id' in data['data']
|
129 |
+
assert data['data']['encoding_type'] == 'BiMO'
|
130 |
+
|
131 |
+
def test_encode_empty_message(self, client, auth_headers):
|
132 |
+
"""Test con mensaje vac铆o"""
|
133 |
+
response = client.post('/api/v1/encode',
|
134 |
+
json={'message': ''},
|
135 |
+
headers=auth_headers)
|
136 |
+
assert response.status_code == 400
|
137 |
+
data = json.loads(response.data)
|
138 |
+
assert data['code'] == 'VALIDATION_ERROR'
|
139 |
+
|
140 |
+
def test_encode_long_message(self, client, auth_headers):
|
141 |
+
"""Test con mensaje muy largo"""
|
142 |
+
long_message = 'A' * 1001 # Excede el l铆mite de 1000 caracteres
|
143 |
+
response = client.post('/api/v1/encode',
|
144 |
+
json={'message': long_message},
|
145 |
+
headers=auth_headers)
|
146 |
+
assert response.status_code == 400
|
147 |
+
|
148 |
+
class TestDecoding:
|
149 |
+
"""Tests para decodificaci贸n de mensajes"""
|
150 |
+
|
151 |
+
def test_decode_nonexistent_package(self, client, auth_headers):
|
152 |
+
"""Test de decodificaci贸n de paquete inexistente"""
|
153 |
+
decode_data = {
|
154 |
+
'package_id': 'BiMO-nonexistent',
|
155 |
+
'measurements': [{'energia_medida': 5.0}]
|
156 |
+
}
|
157 |
+
response = client.post('/api/v1/decode',
|
158 |
+
json=decode_data,
|
159 |
+
headers=auth_headers)
|
160 |
+
assert response.status_code == 404
|
161 |
+
data = json.loads(response.data)
|
162 |
+
assert data['code'] == 'PACKAGE_NOT_FOUND'
|
163 |
+
|
164 |
+
def test_decode_missing_measurements(self, client, auth_headers):
|
165 |
+
"""Test sin mediciones"""
|
166 |
+
response = client.post('/api/v1/decode',
|
167 |
+
json={'package_id': 'BiMO-12345'},
|
168 |
+
headers=auth_headers)
|
169 |
+
assert response.status_code == 400
|
170 |
+
|
171 |
+
class TestPackageManagement:
|
172 |
+
"""Tests para gesti贸n de paquetes"""
|
173 |
+
|
174 |
+
def test_get_packages_empty(self, client, auth_headers):
|
175 |
+
"""Test de historial vac铆o"""
|
176 |
+
response = client.get('/api/v1/packages', headers=auth_headers)
|
177 |
+
assert response.status_code == 200
|
178 |
+
data = json.loads(response.data)
|
179 |
+
assert data['data']['total_count'] == 0
|
180 |
+
|
181 |
+
def test_get_package_details_not_found(self, client, auth_headers):
|
182 |
+
"""Test de detalles de paquete no encontrado"""
|
183 |
+
response = client.get('/api/v1/packages/nonexistent',
|
184 |
+
headers=auth_headers)
|
185 |
+
assert response.status_code == 404
|
186 |
+
|
187 |
+
# Comando para ejecutar los tests:
|
188 |
+
# pytest test_quantumlink_api.py -v --tb=short
|
189 |
+
'''
|
190 |
+
|
191 |
+
# ==================== DOCUMENTACI脫N DE LA API ====================
|
192 |
+
|
193 |
+
api_documentation = """
|
194 |
+
# Documentaci贸n de la API QuantumLink
|
195 |
+
|
196 |
+
## Resumen
|
197 |
+
La API QuantumLink permite codificar y decodificar mensajes usando simulaci贸n cu谩ntica BiMO.
|
198 |
+
|
199 |
+
## Base URL
|
200 |
+
```
|
201 |
+
http://localhost:5000
|
202 |
+
```
|
203 |
+
|
204 |
+
## Autenticaci贸n
|
205 |
+
Todas las rutas protegidas requieren un token de autorizaci贸n en el header:
|
206 |
+
```
|
207 |
+
Authorization: Bearer {token}
|
208 |
+
```
|
209 |
+
|
210 |
+
Para pruebas, usa: `valid_user123`
|
211 |
+
|
212 |
+
## Endpoints
|
213 |
+
|
214 |
+
### GET /
|
215 |
+
Verificaci贸n de salud de la API.
|
216 |
+
|
217 |
+
**Respuesta:**
|
218 |
+
```json
|
219 |
+
{
|
220 |
+
"status": "success",
|
221 |
+
"message": "QuantumLink API est谩 funcionando",
|
222 |
+
"version": "1.0.0",
|
223 |
+
"timestamp": "2025-01-01T12:00:00Z"
|
224 |
+
}
|
225 |
+
```
|
226 |
+
|
227 |
+
### POST /api/v1/encode
|
228 |
+
Codifica un mensaje cu谩ntico.
|
229 |
+
|
230 |
+
**Headers requeridos:**
|
231 |
+
- `Authorization: Bearer {token}`
|
232 |
+
- `Content-Type: application/json`
|
233 |
+
|
234 |
+
**Body:**
|
235 |
+
```json
|
236 |
+
{
|
237 |
+
"message": "MENSAJE A CODIFICAR",
|
238 |
+
"options": {
|
239 |
+
"encoding_type": "BiMO",
|
240 |
+
"priority": "high|medium|low"
|
241 |
+
}
|
242 |
+
}
|
243 |
+
```
|
244 |
+
|
245 |
+
**Respuesta exitosa (201):**
|
246 |
+
```json
|
247 |
+
{
|
248 |
+
"status": "success",
|
249 |
+
"data": {
|
250 |
+
"package_id": "BiMO-12345678",
|
251 |
+
"timestamp": "2025-01-01T12:00:00Z",
|
252 |
+
"qubits_count": 18,
|
253 |
+
"encoding_type": "BiMO"
|
254 |
+
},
|
255 |
+
"message": "Mensaje codificado exitosamente"
|
256 |
+
}
|
257 |
+
```
|
258 |
+
|
259 |
+
### POST /api/v1/decode
|
260 |
+
Decodifica un paquete cu谩ntico.
|
261 |
+
|
262 |
+
**Body:**
|
263 |
+
```json
|
264 |
+
{
|
265 |
+
"package_id": "BiMO-12345678",
|
266 |
+
"measurements": [
|
267 |
+
{"energia_medida": 5.2, "timestamp": "2025-01-01T10:00:00Z"},
|
268 |
+
{"energia_medida": 3.8, "timestamp": "2025-01-01T10:00:01Z"}
|
269 |
+
]
|
270 |
+
}
|
271 |
+
```
|
272 |
+
|
273 |
+
**Respuesta exitosa (200):**
|
274 |
+
```json
|
275 |
+
{
|
276 |
+
"status": "success",
|
277 |
+
"data": {
|
278 |
+
"package_id": "BiMO-12345678",
|
279 |
+
"decoded_message": "MENSAJE DECODIFICADO",
|
280 |
+
"transmission_status": "SUCCESS",
|
281 |
+
"metrics": {
|
282 |
+
"fidelidad": 0.95,
|
283 |
+
"error_rate": 0.05,
|
284 |
+
"coherencia": 0.92
|
285 |
+
},
|
286 |
+
"decoded_at": "2025-01-01T12:05:00Z"
|
287 |
+
}
|
288 |
+
}
|
289 |
+
```
|
290 |
+
|
291 |
+
### GET /api/v1/packages
|
292 |
+
Obtiene el historial de paquetes del usuario.
|
293 |
+
|
294 |
+
**Respuesta:**
|
295 |
+
```json
|
296 |
+
{
|
297 |
+
"status": "success",
|
298 |
+
"data": {
|
299 |
+
"packages": [
|
300 |
+
{
|
301 |
+
"package_id": "BiMO-12345678",
|
302 |
+
"timestamp": "2025-01-01T12:00:00Z",
|
303 |
+
"encoding_type": "BiMO",
|
304 |
+
"qubits_count": 18,
|
305 |
+
"status": "decoded",
|
306 |
+
"metrics": {...}
|
307 |
+
}
|
308 |
+
],
|
309 |
+
"total_count": 1
|
310 |
+
}
|
311 |
+
}
|
312 |
+
```
|
313 |
+
|
314 |
+
### GET /api/v1/packages/{package_id}
|
315 |
+
Obtiene detalles de un paquete espec铆fico.
|
316 |
+
|
317 |
+
## C贸digos de Error
|
318 |
+
|
319 |
+
- `400` - Datos de entrada inv谩lidos (`VALIDATION_ERROR`)
|
320 |
+
- `401` - No autorizado (`UNAUTHORIZED`, `INVALID_TOKEN`)
|
321 |
+
- `403` - Prohibido (`FORBIDDEN`)
|
322 |
+
- `404` - No encontrado (`PACKAGE_NOT_FOUND`, `NOT_FOUND`)
|
323 |
+
- `405` - M茅todo no permitido (`METHOD_NOT_ALLOWED`)
|
324 |
+
- `500` - Error interno (`INTERNAL_ERROR`)
|
325 |
+
|
326 |
+
## L铆mites
|
327 |
+
|
328 |
+
- Mensaje m谩ximo: 1000 caracteres
|
329 |
+
- Qubits m谩ximos por mensaje: 100
|
330 |
+
- Timeout de simulaci贸n: 30 segundos
|
331 |
+
|
332 |
+
## Rate Limiting
|
333 |
+
En producci贸n, se implementar谩 rate limiting por usuario/IP.
|
334 |
+
"""
|
335 |
+
|
336 |
+
if __name__ == "__main__":
|
337 |
+
print("=== Ejecutando ejemplos de QuantumLink ===")
|
338 |
+
|
339 |
+
# Ejecutar ejemplo completo
|
340 |
+
ejemplo_flujo_completo()
|
341 |
+
|
342 |
+
# Ejecutar ejemplo de errores
|
343 |
+
ejemplo_manejo_errores()
|
344 |
+
|
345 |
+
print("\n=== Informaci贸n adicional ===")
|
346 |
+
print("- Revisa los archivos de configuraci贸n para personalizar la API")
|
347 |
+
print("- Ejecuta 'pytest test_quantumlink_api.py -v' para tests automatizados")
|
348 |
+
print("- Consulta la documentaci贸n de la API para m谩s detalles")
|
349 |
+
print("- Usa los ejemplos JavaScript para integraci贸n frontend")
|
350 |
+
print("- Los comandos curl est谩n listos para pruebas manuales"),
|
351 |
+
'Content-Type': 'application/json'
|
352 |
+
})
|
353 |
+
|
354 |
+
def _make_request(self, method: str, endpoint: str, data: Dict = None) -> Dict[str, Any]:
|
355 |
+
"""Realizar una petici贸n HTTP"""
|
356 |
+
url = f"{self.base_url}{endpoint}"
|
357 |
+
|
358 |
+
try:
|
359 |
+
if method.upper() == 'GET':
|
360 |
+
response = self.session.get(url)
|
361 |
+
elif method.upper() == 'POST':
|
362 |
+
response = self.session.post(url, json=data)
|
363 |
+
else:
|
364 |
+
raise ValueError(f"M茅todo HTTP no soportado: {method}")
|
365 |
+
|
366 |
+
response_data = response.json()
|
367 |
+
|
368 |
+
if response.status_code >= 400:
|
369 |
+
raise Exception(f"Error API: {response_data.get('message', 'Error desconocido')}")
|
370 |
+
|
371 |
+
return response_data
|
372 |
+
|
373 |
+
except requests.exceptions.RequestException as e:
|
374 |
+
raise Exception(f"Error de conexi贸n: {str(e)}")
|
375 |
+
|
376 |
+
def health_check(self) -> Dict[str, Any]:
|
377 |
+
"""Verificar el estado de la API"""
|
378 |
+
return self._make_request('GET', '/')
|
379 |
+
|
380 |
+
def encode_message(self, message: str, encoding_type: str = "BiMO", priority: str = "medium") -> Dict[str, Any]:
|
381 |
+
"""Codificar un mensaje cu谩ntico"""
|
382 |
+
data = {
|
383 |
+
"message": message,
|
384 |
+
"options": {
|
385 |
+
"encoding_type": encoding_type,
|
386 |
+
"priority": priority
|
387 |
+
}
|
388 |
+
}
|
389 |
+
return self._make_request('POST', '/api/v1/encode', data)
|
390 |
+
|
391 |
+
def decode_message(self, package_id: str, measurements: List[Dict]) -> Dict[str, Any]:
|
392 |
+
"""Decodificar un paquete cu谩ntico"""
|
393 |
+
data = {
|
394 |
+
"package_id": package_id,
|
395 |
+
"measurements": measurements
|
396 |
+
}
|
397 |
+
return self._make_request('POST', '/api/v1/decode', data)
|
398 |
+
|
399 |
+
def get_packages(self) -> Dict[str, Any]:
|
400 |
+
"""Obtener historial de paquetes"""
|
401 |
+
return self._make_request('GET', '/api/v1/packages')
|
402 |
+
|
403 |
+
def get_package_details(self, package_id: str) -> Dict[str, Any]:
|
404 |
+
"""Obtener detalles de un paquete espec铆fico"""
|
405 |
+
return self._make_request('GET', f'/api/v1/packages/{package_id}')
|
406 |
+
|
407 |
+
# ==================== EJEMPLOS DE USO ====================
|
408 |
+
|
409 |
+
def ejemplo_flujo_completo():
|
410 |
+
"""Ejemplo completo del flujo de codificaci贸n y decodificaci贸n"""
|
411 |
+
print("=== Ejemplo de Flujo Completo QuantumLink ===")
|
412 |
+
|
413 |
+
# Inicializar cliente (token v谩lido para pruebas)
|
414 |
+
client = QuantumLinkClient(auth_token="valid_user123")
|
415 |
+
|
416 |
+
try:
|
417 |
+
# 1. Verificar estado de la API
|
418 |
+
print("1. Verificando estado de la API...")
|
419 |
+
health = client.health_check()
|
420 |
+
print(f" Estado: {health['message']}")
|
421 |
+
|
422 |
+
# 2. Codificar un mensaje
|
423 |
+
print("\n2. Codificando mensaje...")
|
424 |
+
message = "QUANTUM COMMUNICATION IS THE FUTURE"
|
425 |
+
encode_result = client.encode_message(
|
426 |
+
message=message,
|
427 |
+
encoding_type="BiMO",
|
428 |
+
priority="high"
|
429 |
+
)
|
430 |
+
print(f" Mensaje codificado exitosamente")
|
431 |
+
print(f" Package ID: {encode_result['data']['package_id']}")
|
432 |
+
print(f" Qubits utilizados: {encode_result['data']['qubits_count']}")
|
433 |
+
|
434 |
+
package_id = encode_result['data']['package_id']
|
435 |
+
|
436 |
+
# 3. Simular mediciones ruidosas (en un escenario real, vendr铆an del canal cu谩ntico)
|
437 |
+
print("\n3. Simulando mediciones cu谩nticas...")
|
438 |
+
measurements = [
|
439 |
+
{"energia_medida": 5.2, "timestamp": "2025-01-01T10:00:00Z"},
|
440 |
+
{"energia_medida": 3.8, "timestamp": "2025-01-01T10:00:01Z"},
|
441 |
+
{"energia_medida": 4.1, "timestamp": "2025-01-01T10:00:02Z"},
|
442 |
+
{"energia_medida": 2.9, "timestamp": "2025-01-01T10:00:03Z"},
|
443 |
+
]
|
444 |
+
|
445 |
+
# 4. Decodificar el mensaje
|
446 |
+
print("4. Decodificando mensaje...")
|
447 |
+
decode_result = client.decode_message(package_id, measurements)
|
448 |
+
print(f" Mensaje decodificado: {decode_result['data']['decoded_message']}")
|
449 |
+
print(f" Estado de transmisi贸n: {decode_result['data']['transmission_status']}")
|
450 |
+
print(f" M茅tricas cu谩nticas:")
|
451 |
+
for key, value in decode_result['data']['metrics'].items():
|
452 |
+
print(f" {key}: {value}")
|
453 |
+
|
454 |
+
# 5. Obtener historial de paquetes
|
455 |
+
print("\n5. Obteniendo historial...")
|
456 |
+
packages = client.get_packages()
|
457 |
+
print(f" Total de paquetes: {packages['data']['total_count']}")
|
458 |
+
|
459 |
+
# 6. Obtener detalles espec铆ficos del paquete
|
460 |
+
print("6. Obteniendo detalles del paquete...")
|
461 |
+
details = client.get_package_details(package_id)
|
462 |
+
print(f" Paquete encontrado: {details['data']['package']['id_mensaje']}")
|
463 |
+
|
464 |
+
except Exception as e:
|
465 |
+
print(f"Error: {str(e)}")
|
466 |
+
|
467 |
+
def ejemplo_manejo_errores():
|
468 |
+
"""Ejemplo de manejo de errores comunes"""
|
469 |
+
print("\n=== Ejemplo de Manejo de Errores ===")
|
470 |
+
|
471 |
+
client = QuantumLinkClient(auth_token="invalid_token")
|
472 |
+
|
473 |
+
try:
|
474 |
+
# Intentar codificar con token inv谩lido
|
475 |
+
client.encode_message("Test message")
|
476 |
+
except Exception as e:
|
477 |
+
print(f"Error esperado con token inv谩lido: {str(e)}")
|
478 |
+
|
479 |
+
# Cliente sin autenticaci贸n
|
480 |
+
client_no_auth = QuantumLinkClient()
|
481 |
+
try:
|
482 |
+
client_no_auth.encode_message("Test message")
|
483 |
+
except Exception as e:
|
484 |
+
print(f"Error esperado sin autenticaci贸n: {str(e)}")
|
485 |
+
|
486 |
+
# ==================== EJEMPLOS JAVASCRIPT ====================
|
487 |
+
|
488 |
+
javascript_examples = """
|
489 |
+
// Ejemplo de cliente JavaScript para frontend
|
490 |
+
|
491 |
+
class QuantumLinkAPI {
|
492 |
+
constructor(baseURL = 'http://localhost:5000', authToken = null) {
|
493 |
+
this.baseURL = baseURL;
|
494 |
+
this.authToken = authToken;
|
495 |
+
}
|
496 |
+
|
497 |
+
async makeRequest(method, endpoint, data = null) {
|
498 |
+
const url = `${this.baseURL}${endpoint}`;
|
499 |
+
const options = {
|
500 |
+
method: method,
|
501 |
+
headers: {
|
502 |
+
'Content-Type': 'application/json',
|
503 |
+
}
|
504 |
+
};
|
505 |
+
|
506 |
+
if (this.authToken) {
|
507 |
+
options.headers['Authorization'] = `Bearer ${this.authToken}`;
|
508 |
+
}
|
509 |
+
|
510 |
+
if (data) {
|
511 |
+
options.body = JSON.stringify(data);
|
512 |
+
}
|
513 |
+
|
514 |
+
try {
|
515 |
+
const response = await fetch(url, options);
|
516 |
+
const responseData = await response.json();
|
517 |
+
|
518 |
+
if (!response.ok) {
|
519 |
+
throw new Error(responseData.message || 'Error desconocido');
|
520 |
+
}
|
521 |
+
|
522 |
+
return responseData;
|
523 |
+
} catch (error) {
|
524 |
+
console.error('Error en la petici贸n:', error);
|
525 |
+
throw error;
|
526 |
+
}
|
527 |
+
}
|
528 |
+
|
529 |
+
async encodeMessage(message, options = {}) {
|
530 |
+
const data = {
|
531 |
+
message: message,
|
532 |
+
options: {
|
533 |
+
encoding_type: options.encoding_type || 'BiMO',
|
534 |
+
priority: options.priority || 'medium'
|
535 |
+
}
|
536 |
+
};
|
537 |
+
return await this.makeRequest('POST', '/api/v1/encode', data);
|
538 |
+
}
|
539 |
+
|
540 |
+
async decodeMessage(packageId, measurements) {
|
541 |
+
const data = {
|
542 |
+
package_id: packageId,
|
543 |
+
measurements: measurements
|
544 |
+
};
|
545 |
+
return await this.makeRequest('POST', '/api/v1/decode', data);
|
546 |
+
}
|
547 |
+
|
548 |
+
async getPackages() {
|
549 |
+
return await this.makeRequest('GET', '/api/v1/packages');
|
550 |
+
}
|
551 |
+
}
|
552 |
+
|
553 |
+
// Ejemplo de uso en React/Vue/Angular
|
554 |
+
async function ejemploFrontend() {
|
555 |
+
const api = new QuantumLinkAPI('http://localhost:5000', 'valid_user123');
|
556 |
+
|
557 |
+
try {
|
558 |
+
// Codificar mensaje
|
559 |
+
const encodeResult = await api.encodeMessage('HELLO QUANTUM WORLD');
|
560 |
+
console.log('Mensaje codificado:', encodeResult);
|
561 |
+
|
562 |
+
// Simular mediciones
|
563 |
+
const measurements = [
|
564 |
+
{energia_medida: 4.5, timestamp: new Date().toISOString()},
|
565 |
+
{energia_medida: 3.2, timestamp: new Date().toISOString()}
|
566 |
+
];
|
567 |
+
|
568 |
+
// Decodificar
|
569 |
+
const decodeResult = await api.decodeMessage(
|
570 |
+
encodeResult.data.package_id,
|
571 |
+
measurements
|
572 |
+
);
|
573 |
+
console.log('Mensaje decodificado:', decodeResult);
|
574 |
+
|
575 |
+
} catch (error) {
|
576 |
+
console.error('Error:', error.message);
|
577 |
+
}
|
578 |
+
}
|
579 |
+
"""
|
580 |
+
|
581 |
+
# ==================== EJEMPLOS CURL ====================
|
582 |
+
|
583 |
+
curl_examples = """
|
584 |
+
# Ejemplos de comandos curl para probar la API
|
585 |
+
|
586 |
+
# 1. Verificar estado de la API
|
587 |
+
curl -X GET http://localhost:5000/
|
588 |
+
|
589 |
+
# 2. Codificar un mensaje
|
590 |
+
curl -X POST http://localhost:5000/api/v1/encode \\
|
591 |
+
-H "Content-Type: application/json" \\
|
592 |
+
-H "Authorization: Bearer valid_user123" \\
|
593 |
+
-d '{
|
594 |
+
"message": "QUANTUM TEST MESSAGE",
|
595 |
+
"options": {
|
596 |
+
"encoding_type": "BiMO",
|
597 |
+
"priority": "high"
|
598 |
+
}
|
599 |
+
|