Saltar a contenido

Ejemplos en Python – API de Salud y Fitness

Python facilita la interacción con APIs RESTful como API de Salud y Fitness. A continuación, encontrará ejemplos que utilizan múltiples bibliotecas HTTP de Python tanto para solicitudes síncronas como asíncronas.


1. Utilizando requests (Síncrono, más común)

import requests

API_KEY = "YOUR_API_KEY"
url = "https://api.hefitapi.com/api/v1/bmi"
params = {
    "height": 178,
    "weight": 82,
    "units": "metric",
    "lang": "en"
}
headers = {"X-API-Key": API_KEY}

response = requests.get(url, headers=headers, params=params)
data = response.json()

print(data)

Ejemplo de solicitud POST:

import requests

API_KEY = "YOUR_API_KEY"
url = "https://api.hefitapi.com/api/v1/bmi/post"
payload = {
    "height": 178,
    "weight": 82,
    "units": "metric"
}
headers = {
    "X-API-Key": API_KEY,
    "Content-Type": "application/json"
}

response = requests.post(url, headers=headers, json=payload)
data = response.json()

print(data)

2. Utilizando httpx (Síncrono y Asíncrono)

Ejemplo de GET síncrono:

import httpx

API_KEY = "YOUR_API_KEY"
url = "https://api.hefitapi.com/api/v1/bmi"
params = {"height": 178, "weight": 82, "units": "metric", "lang": "en"}
headers = {"X-API-Key": API_KEY}

with httpx.Client() as client:
    response = client.get(url, headers=headers, params=params)
    data = response.json()
    print(data)

Ejemplo de GET asíncrono:

import httpx
import asyncio

API_KEY = "YOUR_API_KEY"
url = "https://api.hefitapi.com/api/v1/bmi"
params = {"height": 178, "weight": 82, "units": "metric", "lang": "en"}
headers = {"X-API-Key": API_KEY}

async def fetch_bmi():
    async with httpx.AsyncClient() as client:
        response = await client.get(url, headers=headers, params=params)
        data = response.json()
        print(data)

asyncio.run(fetch_bmi())

Ejemplo de POST (asíncrono):

async def post_bmi():
    payload = {"height": 178, "weight": 82, "units": "metric"}
    async with httpx.AsyncClient() as client:
        response = await client.post(url + "/post", headers=headers, json=payload)
        data = response.json()
        print(data)

asyncio.run(post_bmi())

3. Utilizando urllib (Biblioteca estándar)

import json
from urllib import request, parse

API_KEY = "YOUR_API_KEY"
url = "https://api.hefitapi.com/api/v1/bmi"
params = {"height": 178, "weight": 82, "units": "metric", "lang": "en"}
query_string = parse.urlencode(params)
full_url = f"{url}?{query_string}"

req = request.Request(full_url, headers={"X-API-Key": API_KEY})
with request.urlopen(req) as response:
    data = json.load(response)
    print(data)

Ejemplo de solicitud POST utilizando urllib:

payload = json.dumps({"height": 178, "weight": 82, "units": "metric"}).encode("utf-8")
req = request.Request(url + "/post", data=payload, method="POST")
req.add_header("Content-Type", "application/json")
req.add_header("X-API-Key", API_KEY)

with request.urlopen(req) as response:
    data = json.load(response)
    print(data)

import aiohttp
import asyncio

API_KEY = "YOUR_API_KEY"
url = "https://api.hefitapi.com/api/v1/bmi"
params = {"height": 178, "weight": 82, "units": "metric", "lang": "en"}
headers = {"X-API-Key": API_KEY}

async def fetch_bmi():
    async with aiohttp.ClientSession() as session:
        async with session.get(url, headers=headers, params=params) as resp:
            data = await resp.json()
            print(data)

asyncio.run(fetch_bmi())

Ejemplo de POST (aiohttp):

async def post_bmi():
    payload = {"height": 178, "weight": 82, "units": "metric"}
    async with aiohttp.ClientSession() as session:
        async with session.post(url + "/post", headers=headers, json=payload) as resp:
            data = await resp.json()
            print(data)

asyncio.run(post_bmi())

5. Notas y Mejores Prácticas

  • Siempre reemplace YOUR_API_KEY con su clave de API real.
  • Utilice el parámetro lang para el soporte multilingüe (en, fr, de, es, etc.).
  • Para producción, considere la gestión de conexiones (cliente httpx) y las solicitudes asíncronas para el rendimiento.
  • Maneje los errores con gracia: códigos de estado HTTP, tiempos de espera y excepciones.
  • Las respuestas incluyen señales de riesgo, planes de acción y metadatos empresariales cuando están disponibles.

Próximos pasos

Consulte otros ejemplos específicos del lenguaje:

¡Comience a integrar la API de Salud y Fitness en sus aplicaciones de Python hoy mismo!


API de Salud y Fitness Impulsando la infraestructura digital de salud moderna