Ejecuta miles de peticiones a una API externa simultáneamente en segundos en lugar de esperar horas secuencialmente.
Run thousands of requests to an external API concurrently in seconds instead of waiting hours sequentially.
Este ejercicio es solo para aprendizaje y pruebas. No ejecutes scripts contra datos reales, ambientes de producción, APIs externas, portales con login, datos sensibles, sistemas críticos o repositorios empresariales sin autorización, respaldos, pruebas previas, permisos mínimos, control de cambios y cumplimiento de los protocolos de ciberseguridad de tu organización.
This exercise is for learning and testing only. Do not run scripts against real data, production environments, external APIs, login portals, sensitive data, critical systems, or enterprise repositories without authorization, backups, prior testing, least-privilege permissions, change control, and compliance with your organization's cybersecurity protocols.
Aprender a usar asyncio y aiohttp para consultar varias URLs al mismo tiempo, controlar errores y consolidar las respuestas en un DataFrame.
Learn how to use asyncio and aiohttp to query multiple URLs at the same time, handle errors, and consolidate responses into a DataFrame.
| request_id | url | expected_status |
|---|---|---|
| 1 | https://api.example.com/customer/1001 | 200 |
| 2 | https://api.example.com/customer/1002 | 200 |
| 3 | https://api.example.com/customer/9999 | 404 |
import asyncio
import aiohttp
async def fetch_data(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
return await response.json()| request_id | status | records_returned | seconds |
|---|---|---|---|
| 1 | success | 1 | 0.24 |
| 2 | success | 1 | 0.22 |
| 3 | not_found | 0 | 0.19 |
# ==========================================================
# Python Advanced Topic 07
# High-Performance Asynchronous API Requests
# ==========================================================
# pip install aiohttp pandas
import asyncio
import aiohttp
import pandas as pd
import time
urls = [
{"request_id": 1, "url": "https://jsonplaceholder.typicode.com/users/1"},
{"request_id": 2, "url": "https://jsonplaceholder.typicode.com/users/2"},
{"request_id": 3, "url": "https://jsonplaceholder.typicode.com/users/3"},
]
async def fetch_data(session, item):
start = time.perf_counter()
try:
async with session.get(item["url"], timeout=10) as response:
payload = await response.json()
return {
"request_id": item["request_id"],
"url": item["url"],
"status_code": response.status,
"name": payload.get("name"),
"seconds": round(time.perf_counter() - start, 3),
"result": "success" if response.status == 200 else "review"
}
except Exception as exc:
return {
"request_id": item["request_id"],
"url": item["url"],
"status_code": None,
"name": None,
"seconds": round(time.perf_counter() - start, 3),
"result": f"error: {exc}"
}
async def main():
async with aiohttp.ClientSession() as session:
tasks = [fetch_data(session, item) for item in urls]
results = await asyncio.gather(*tasks)
df = pd.DataFrame(results)
df.to_csv("api_async_results.csv", index=False)
print(df)
asyncio.run(main())request_id status_code name seconds result 0 1 200 Leanne Graham 0.214 success 1 2 200 Ervin Howell 0.208 success 2 3 200 Clementine Bauch 0.219 success
La asincronía permite acelerar procesos que dependen de espera de red sin saturar el CPU. Es clave para integraciones modernas con APIs.
Asynchronous execution speeds up network-bound processes without overloading the CPU. It is essential for modern API integrations.