Comece agoraComece grátis

Quando APIs exigem autenticação

Quando uma API externa requer uma chave de API, essa chave deve ficar no ambiente do servidor e ser anexada apenas no cabeçalho da requisição de saída. O cliente nunca envia nem recebe a chave. Neste exercício, você vai adicionar suporte opcional a chave de API à ferramenta convert_currency do servidor de câmbio.

A Frankfurter API não exige chave para uso básico, mas muitas APIs exigem. Você vai ler uma chave opcional do ambiente (por exemplo, CURRENCY_API_KEY) e, se estiver definida, adicioná-la à requisição como um cabeçalho Authorization: Bearer.

Um servidor MCP já foi instanciado e armazenado na variável mcp. O módulo os já foi importado para você.

Este exercicio faz parte do curso

Introdução ao Model Context Protocol (MCP)

Ver curso

Instruções do exercicio

  • Leia a chave de API "CURRENCY_API_KEY" das variáveis de ambiente e adicione-a ao cabeçalho "Authorization" com o valor "Bearer " mais a chave na requisição.
  • Passe os cabeçalhos na requisição GET da API.

exercicio interativo prático

Tente este exercicio completando este código de exemplo.

@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"))
Editar e Executar Código