BaşlayınÜcretsiz başlayın

API'ler Kimlik Doğrulama Gerektirdiğinde

Dış bir API bir API anahtarı gerektirdiğinde, anahtar sunucunun ortamında tutulmalı ve yalnızca giden istek üstbilgisine eklenmelidir. İstemci bu anahtarı asla göndermez veya almaz. Bu egzersizde para birimi sunucusunun convert_currency aracına isteğe bağlı API anahtarı desteği ekleyeceksin.

Frankfurter API temel kullanım için anahtar gerektirmez, ancak birçok API gerektirir. Ortamdan (ör. CURRENCY_API_KEY) isteğe bağlı bir anahtar okuyacak ve ayarlıysa isteğe Authorization: Bearer üstbilgisi olarak ekleyeceksin.

Bir MCP sunucusu zaten başlatıldı ve mcp değişkeninde saklandı. os modülü senin için içe aktarıldı.

Bu egzersiz, kursun bir parçasıdır

Model Context Protocol (MCP) Giriş

Kursa Göz Atın

Egzersiz talimatları

  • Ortam değişkenlerinden "CURRENCY_API_KEY" API anahtarını oku ve isteğe, anahtarın önüne "Bearer " ekleyerek "Authorization" üstbilgisi olarak ekle.
  • Üstbilgileri API GET isteğinde geçir.

Uygulamalı etkileşimli egzersiz

Bu egzersizi bu örnek kodu tamamlayarak deneyin.

@mcp.tool()
def convert_currency(amount: float, from_currency: str, to_currency: str) -> str:
    """Convert an amount from one currency to another using current exchange rates."""
    url = f"https://api.frankfurter.dev/v1/latest?base={from_currency}&symbols={to_currency}"
    # Read optional API key from the server's environment
    headers = {}
    api_key = os.environ.get(____)
    if api_key:
        headers["Authorization"] = f"Bearer {____}"
    try:
        # Pass headers (and timeout) to the request; key never goes in the URL
        r = requests.get(url, ____=____, timeout=10)
        r.raise_for_status()
        data = r.json()
        rate = data["rates"].get(to_currency)
        if rate is None:
            return f"Could not find exchange rate for {from_currency} to {to_currency}"
        return f"{amount} {from_currency} = {amount * rate:.2f} {to_currency} (Rate: {rate})"
    except requests.exceptions.RequestException as e:
        return f"Error converting currency: {e}"

print(convert_currency(10, "USD", "EUR"))
Kodu Düzenle ve Çalıştır