1Kurulum

REST API için requests, WebSocket için python-socketio kütüphanelerini kurun:

pip install requests python-socketio[asyncio_client]

API key almak için ücretsiz hesap oluşturun.

2REST API — Anlık Fiyat Sorgulama

HTTP GET isteğiyle istediğiniz sembolün anlık alış/satış fiyatını alın. Kimlik doğrulama x-api-key header'ıyla yapılır.

Tek Sembol Sorgusu

Python — REST API
import requests

API_KEY = "hapi_xxxx"  # Dashboard'dan alın
BASE_URL = "https://altinapi.com/api"

headers = {"x-api-key": API_KEY}

# Has altın fiyatı
response = requests.get(f"{BASE_URL}/prices/ALTIN", headers=headers)
data = response.json()

print(f"Has Altın — Alış: {data['bid']} TL, Satış: {data['ask']} TL")
# Çıktı: Has Altın — Alış: 3842.50 TL, Satış: 3848.00 TL

Tüm Fiyatları Çekme

Python — Tüm Semboller
import requests

headers = {"x-api-key": "hapi_xxxx"}
response = requests.get("https://altinapi.com/api/prices", headers=headers)
prices = response.json()

# Altın ve maden fiyatlarını filtrele
for price in prices:
    if price["category"] == "MADEN":
        print(f"{price['symbol']:12} Alış: {price['bid']:>10} | Satış: {price['ask']:>10}")

3WebSocket — Gerçek Zamanlı Fiyatlar

WebSocket bağlantısıyla fiyatlar değiştiği anda uygulamanıza push edilir. Polling'e gerek yoktur.

Python — WebSocket (python-socketio)
import socketio
import time

# Senkron istemci (script için)
sio = socketio.Client()

@sio.event
def connect():
    print("Bağlandı!")

@sio.on("prices:snapshot")
def on_snapshot(data):
    print("İlk fiyatlar alındı:")
    for price in data["data"]:
        print(f"  {price['symbol']}: {price['bid']} / {price['ask']}")

@sio.on("prices:update")
def on_update(data):
    for price in data["data"]:
        print(f"Güncelleme — {price['symbol']}: {price['bid']} / {price['ask']}")

# /public namespace — API key gerekmez (landing gösterimi için)
sio.connect("https://altinapi.com", namespaces=["/public"])
sio.wait()

Kimlik Doğrulamalı Bağlantı (API Key ile)

Python — Authenticated WebSocket
import socketio

sio = socketio.Client()

# API key ile kimlik doğrulama
sio.connect(
    "https://altinapi.com",
    auth={"apiKey": "hapi_xxxx"}
)

# Sadece belirli sembollere abone ol
sio.emit("subscribe", ["ALTIN", "USDTRY", "CEYREK_YENI"])
sio.wait()

4Async WebSocket (asyncio)

FastAPI veya asyncio tabanlı projelerde async istemci kullanın:

Python — Async WebSocket
import asyncio
import socketio

sio = socketio.AsyncClient()

@sio.on("prices:snapshot")
async def on_snapshot(data):
    for price in data["data"]:
        print(f{price['symbol']}: {price['bid']})

@sio.on("prices:update")
async def on_update(data):
    for price in data["data"]:
        print(f"Güncelleme: {price['symbol']} → {price['bid']}")

async def main():
    await sio.connect("https://altinapi.com", namespaces=["/public"])
    await sio.wait()

asyncio.run(main())

5Hata Yönetimi

Python — Error Handling
import requests
from requests.exceptions import RequestException

def get_gold_price(api_key: str) -> dict | None:
    try:
        response = requests.get(
            "https://altinapi.com/api/prices/ALTIN",
            headers={"x-api-key": api_key},
            timeout=5
        )
        response.raise_for_status()
        return response.json()
    except requests.exceptions.HTTPError as e:
        if e.response.status_code == 401:
            print("Geçersiz API key")
        elif e.response.status_code == 429:
            print("Rate limit aşıldı")
        return None
    except RequestException as e:
        print(f"Bağlantı hatası: {e}")
        return None

Diğer Diller