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

# Call an API with a key

> Let a listed actor call a service that needs an API key, without the key ever appearing in its code, state or calls

By the end of this page, your actor calls an API that needs a key, and the key stays out of everything the public can read. Most products worth selling call a service like that: a social network, a data provider, a model host.

An actor's code, its state and every call to it are public, so a key can't go in any of them. Instead it goes in Cowboy's **secret store**, and the actor marks where it belongs. A runner, the machine that makes the request for the actor, fills it in at the last moment.

It takes four pieces: the code, a manifest, a deploy and the key.

## 1. Mark where the key goes

`runner.secret(name, prefix=..., suffix=...)` stands in for the key. The job the actor sends carries only the text around it, and the runner puts the value in when it makes the request. It works in a URL, a header or the request body:

```python theme={"system"}
from cowboy_sdk import HOUR, Actor, public, runner

USER_URL = "https://api.x.com/2/users/by/username/"


class Lookup(Actor):
    @public
    @runner.continuation(timeout=HOUR)
    async def followers(self, username: str) -> object:
        reply = await runner.http(
            url=USER_URL + username + "?user.fields=public_metrics",
            method="GET",
            headers={
                "Authorization": runner.secret("X_BEARER_TOKEN", prefix="Bearer ")
            },
        )
        return reply.data
```

For an API that takes its key in the URL, wrap the whole URL: `url=runner.secret("YOUTUBE_API_KEY", prefix="https://...&key=")`. Pass the URL as `url=`, because the secret can't fill a positional argument.

A test sees the secret's name and where it goes, never a value. In a `SimulatedChain` test, the last job's `secret_slots` lists them:

```python theme={"system"}
from cowboy_sdk import codec, mock_host
from cowboy_sdk.testing import SimulatedChain


def test_the_key_is_not_in_the_job() -> None:
    actor = Lookup()
    chain = SimulatedChain(actor)
    mock_host.seed_actor_owner(mock_host.context()["sender"])
    chain.call(actor.followers, codec.encode("XDevelopers"))
    job = chain.jobs()[-1]["payload"]["kwargs"]
    assert job["headers"]["Authorization"] == "Bearer "
    assert [slot["key"] for slot in job["secret_slots"]] == ["X_BEARER_TOKEN"]
```

## 2. Allow the host

Web requests need the `http.fetch` permission, which names the hosts the actor may reach. Ask for it in a manifest, saved as `manifest.json` in the project:

```json theme={"system"}
{"entitlements": [{"id": "http.fetch", "params": {"allowlist_domains": ["api.x.com"]}}]}
```

Name only the hosts you call. A request to any other host is refused.

## 3. Deploy

```bash theme={"system"}
cowboy deploy lookup --manifest-json manifest.json \
  --max-spend-usd 5 --no-owner-funding
```

```text Output theme={"system"}
  🤠 Yeehaw! lookup is live on cloud

  Actor    0x2858…c20c
  Inspect  cowboy actor inspect lookup
```

The manifest is fixed at deploy. To reach another host later, deploy again with a new manifest.

`--max-spend-usd` caps what the deploy takes from your wallet. `--no-owner-funding` keeps the actor from drawing on your wallet when its own balance runs short, or pass `--owner-funding-cap-usd` to allow it up to a limit ([Keep it funded](https://docs.cowboy.inc/build/deploy.md#keep-it-funded)).

## 4. Add the key

Add the key for the address `deploy` printed. The command never takes the value: it opens a page on Cloud where you type it, and the page encrypts it before saving it.

```bash theme={"system"}
cowboy secrets add X_BEARER_TOKEN --actor <actor address> \
  --dashboard-url https://cloud.cowboy.inc
```

```text Output theme={"system"}
https://cloud.cowboy.inc/secrets/add/r/…
Code: …
Expires at: …
✓ Saved X_BEARER_TOKEN. Readers: 0x2858…c20c
```

`Readers` lists the actors the key is released to. Only those actors' jobs can use it.

> [!NOTE]
>
> **Coming soon:** adding a key without a browser, so a coding agent or a script can do this step.

A new deploy gets a new address, so when you ship a new version with `cowboy deploy --new`, add the key for the new address too.

## Whose key a listed actor uses

The key you add is yours. Every hirer's requests go out with it, so they all count against your account with that service and its rate limits. Set the actor's [`@limit`](https://docs.cowboy.inc/build/sdk/safety) with that in mind, and pick a service whose terms allow it.

> [!NOTE]
>
> **Coming soon:** listings that ask each hirer for their own key during setup, and hires that run their own copy of your actor with your key.

What a key can and can't protect against, from a hirer's side, is in [Your keys and your data](https://docs.cowboy.inc/hire/keys-and-data.md#secrets).

## Next

* [Call models, the web and tools](https://docs.cowboy.inc/developers/submitting-jobs.md#secrets) covers runner jobs and `runner.secret` in full.
* [Walkthrough: sell a social metrics product](https://docs.cowboy.inc/sell/social-metrics-walkthrough.md#use-an-api-that-needs-a-key) has YouTube and X versions of a listed actor.
* [Package and submit a listing](https://docs.cowboy.inc/sell/package-and-submit.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.