> ## Documentation Index
> Fetch the complete documentation index at: https://docs.portkey.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Advanced code snippets and examples

> Advanced code snippets and examples for the Agent Gateway

<Info>
  Modify the API key permissions and turn on the **Agent Gateway** toggle for your API key. See the [Quickstart](/product/agent-gateway/quickstart) for where to configure this in the app. Make sure the `agents.invoke` scope is enabled.
</Info>

## Introduction

The [Quickstart](/product/agent-gateway/quickstart) guide provides a basic example of how to use the Agent Gateway.

This guide provides more examples and code snippets to help you get started.

## Fetching the agent card

<CodeGroup>
  ```shell cURL theme={"system"}
  curl --location --request POST 'https://agents.portkey.ai/v1/agent/{agent-slug}/.well-known/agent.json' \
  --header 'Content-Type: application/json' \
  --header 'x-portkey-api-key: {PORTKEY_API_KEY}'
  ```

  ```python python theme={"system"}
  import asyncio
  import json

  from a2a.client import A2ACardResolver
  import httpx

  BASE_URL = "https://agents.portkey.ai/v1/agent/{agent-slug}"
  API_KEY = "{PORTKEY_API_KEY}"


  async def log_httpx_request(request: httpx.Request) -> None:
      try:
          body = request.content.decode("utf-8") if request.content else "<empty>"
      except Exception:
          body = "<streaming or unreadable body>"
      print(f"[httpx] {request.method} {request.url}")
      print(f"[httpx] body: {body}\n")


  async def main() -> None:
      print(f"Fetching agent card from {BASE_URL}...")
      async with httpx.AsyncClient(
          base_url=BASE_URL,
          headers={"x-portkey-api-key": API_KEY},
          event_hooks={"request": [log_httpx_request]},
      ) as client:
          resolver = A2ACardResolver(httpx_client=client, base_url=BASE_URL)
          agent_card = await resolver.get_agent_card()
          print(json.dumps(agent_card.model_dump(mode="json", exclude_none=True), indent=2))


  if __name__ == "__main__":
      asyncio.run(main())
  ```

  ```javascript JavaScript theme={"system"}
  import {
    DefaultAgentCardResolver,
    ClientFactory,
    ClientFactoryOptions,
  } from "@a2a-js/sdk/client";

  const BASE_URL = "https://agents.portkey.ai/v1/agent/{agent-slug}";
  const API_KEY = "{PORTKEY_API_KEY}";

  class HeaderAuthInterceptor {
    async before(args) {
      args.options = {
        ...args.options,
        serviceParameters: {
          ...(args.options?.serviceParameters || {}),
          "x-portkey-api-key": API_KEY,
        },
      };
    }

    async after() {}
  }

  function createAuthenticatedFetch() {
    return async (input, init = {}) => {
      const headers = new Headers(init.headers || {});
      headers.set("x-portkey-api-key", API_KEY);
      return fetch(input, { ...init, headers });
    };
  }

  async function main() {
    console.log(`Fetching agent card from ${BASE_URL}...`);

    const authFetch = createAuthenticatedFetch();
    const resolverBaseUrl = BASE_URL.endsWith("/") ? BASE_URL : `${BASE_URL}/`;

    const options = ClientFactoryOptions.createFrom(
      ClientFactoryOptions.default,
      {
        cardResolver: new DefaultAgentCardResolver({
          fetchImpl: authFetch,
        }),
        clientConfig: { interceptors: [new HeaderAuthInterceptor()] },
      },
    );

    const factory = new ClientFactory(options);
    const client = await factory.createFromUrl(resolverBaseUrl);

    const card = client.agentCard;

    if (!card) {
      throw new Error("Unable to read agent card from SDK client instance.");
    }

    console.log(JSON.stringify(card, null, 2));
  }

  main().catch((error) => {
    console.error(error);
    process.exit(1);
  });
  ```
</CodeGroup>

## Invoking the agent

### JSON-RPC examples

```shell cURL theme={"system"}
curl --location 'https://agents.portkey.ai/v1/agent/{agent-slug}' \
--header 'Content-Type: application/json' \
--header 'x-portkey-api-key: {PORTKEY_API_KEY}' \
--data '{
    "jsonrpc": "2.0",
    "id": "req-1",
    "method": "tasks/send",
    "params": {
        "id": "task-header-1",
        "message": {
            "role": "user",
            "parts": [
                {
                    "type": "text",
                    "text": "echo Hello from header auth"
                }
            ]
        }
    }
}'
```

```python python theme={"system"}
import asyncio
import json
from uuid import uuid4

import httpx

BASE_URL = "https://agents.portkey.ai/v1/agent/header-based-authentication"
API_KEY = "+/gW5Oclr7Y9z01jEOVBaAfKZxfz"


async def log_httpx_request(request: httpx.Request) -> None:
    try:
        body = request.content.decode("utf-8") if request.content else "<empty>"
    except Exception:
        body = "<streaming or unreadable body>"
    print(f"[httpx] {request.method} {request.url}")
    print(f"[httpx] body: {body}\n")


async def main() -> None:
    print(f"Connecting to A2A agent at {BASE_URL}...")
    message_text = "echo Hello from header auth"
    task_id = f"task-{uuid4().hex[:12]}"
    request_id = f"req-{uuid4().hex[:8]}"
    payload = {
        "jsonrpc": "2.0",
        "id": request_id,
        "method": "tasks/send",
        "params": {
            "id": task_id,
            "message": {
                "role": "user",
                "parts": [
                    {
                        "type": "text",
                        "text": message_text,
                    }
                ],
            },
        },
    }

    async with httpx.AsyncClient(
        base_url=BASE_URL,
        headers={
            "x-portkey-api-key": API_KEY,
            "Content-Type": "application/json",
        },
        event_hooks={"request": [log_httpx_request]},
    ) as httpx_client:
        print(f"Sending task with message: {message_text}")
        response = await httpx_client.post("", json=payload)
        response.raise_for_status()
        print(json.dumps(response.json(), indent=2))


if __name__ == "__main__":
    asyncio.run(main())
```

```javascript JavaScript theme={"system"}
const BASE_URL =
  process.env.BASE_URL || "https://agents.portkey.ai/v1/agent/{agent-slug}";
const API_KEY = process.env.API_KEY || "{PORTKEY_API_KEY}";
const MESSAGE_TEXT = process.env.MESSAGE_TEXT || "echo Hello from header auth";

async function main() {
  console.log(`Connecting to A2A agent at ${BASE_URL}...`);
  console.log(`Sending task with message: ${MESSAGE_TEXT}`);

  const payload = {
    jsonrpc: "2.0",
    id: `req-${crypto.randomUUID().slice(0, 8)}`,
    method: "tasks/send",
    params: {
      id: `task-${crypto.randomUUID().slice(0, 12)}`,
      message: {
        role: "user",
        parts: [{ type: "text", text: MESSAGE_TEXT }],
      },
    },
  };

  const response = await fetch(BASE_URL, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "x-portkey-api-key": API_KEY,
    },
    body: JSON.stringify(payload),
  });

  if (!response.ok) {
    throw new Error(
      `HTTP ${response.status}: ${response.statusText} while calling tasks/send`,
    );
  }

  const result = await response.json();
  console.log(JSON.stringify(result, null, 2));
}

main().catch((error) => {
  console.error(error);
  process.exit(1);
});
```

## Further reading

<CardGroup cols={2}>
  <Card title="Quickstart" icon="rocket" href="/product/agent-gateway/quickstart">
    Get started with the Agent Gateway by registering your first agent.
  </Card>

  <Card title="Agent Registry" icon="book" href="/product/agent-gateway/registry">
    Manage your agent integrations and control access to agents and their skills.
  </Card>

  <Card title="Agent Servers" icon="server" href="/product/agent-gateway/servers">
    Learn how virtual agent servers work and how to host your own.
  </Card>
</CardGroup>
