---
title: Call an external API with an API key
description: Call an API with a key you stored on the dashboard: declare the upstream and call it through the gateway, or list a host that needs no key.
slug: /guides/call-an-external-api-with-an-api-key
order: 7
visibility: public
redirects_from: []
---

# Call an external API with an API key

Prompt:

> I stored my weather service's API key on the Turn Zero dashboard as WEATHER_API_KEY. Use it to fetch the forecast for each listing.

Also works:

- "Call the Anthropic API from the backend with the key I saved on the dashboard as ANTHROPIC_KEY."
- "Post every new order to our fulfilment partner's webhook. Its key is on the dashboard as PARTNER_KEY."
- "The payments key leaked. I stored the new one on the dashboard under the same name."

The key stays on the platform: stored from the dashboard or by your AI tool ([step 1](#1-store-the-api-key)), then declared by your AI tool as an upstream ([step 2](#2-declare-the-upstream)). Your route then calls the upstream through the gateway, which adds the key, so your code never holds it ([step 3](#3-call-it-from-a-route)).

Declare the upstream before your code calls the outside API. The gateway refuses a call to an upstream name that is not declared, with 404 `undeclared_upstream`. A host that needs no key goes in the manifest's `egress` list instead ([A host that needs no key](#a-host-that-needs-no-key)).

No one call stores the key and declares the upstream. With `declare_outbound_api`, your AI tool stores the key first, then declares:

1. `store_secret` with the key's name, then the command line its response returns, where it returns one, run once. For a key stored on the dashboard, `list_secrets` confirms the name instead.
2. `declare_outbound_api`, with that name as its `credential_name`.

An entry in the manifest's `upstreams` accepts a name not yet stored ([Declare in the manifest](#declare-in-the-manifest)).

## If your code reads an API key from a variable

Use an upstream for an outside API key. Bind a value your code uses itself, such as a webhook signing secret, in the manifest's `settings`. Bind an API key only if its host is fixed in code the task forbids changing. [Step 1's table](#1-store-the-api-key) compares these routes.

Reading an API key from `process.env` does not by itself mean the application should receive the stored value. Keep the provider's key out of chat and code. Store it by name with `store_secret`, or confirm its name with `list_secrets` if it is already stored.

- **The application's own code:** for new code or code you change, declare the API with `declare_outbound_api`, call its gateway route, and send `TURNZERO_CLOUD_APP_TOKEN` as a bearer, and stop reading the provider's key. Code that already reads its base URL and key from settings and sends the key as a bearer can stay as it is ([the code change](#move-code-that-reads-the-key-from-an-environment-variable)).
- **An unchanged SDK:** it must read a base URL setting and send its key as `Authorization: Bearer`. Declare both settings with `sdk_settings`. Keep the key setting's name only if the SDK sends it as that bearer. For Anthropic, use `ANTHROPIC_AUTH_TOKEN`, not `ANTHROPIC_API_KEY` ([SDK example](#an-unchanged-sdk)).
- **An API host fixed in code the task forbids changing:** the key must be stored at the application's scope for that environment. Bind its name in the manifest's `settings` and list the host in `egress` ([the exception](/cloud/getting-started/store-a-secret/#the-rule-in-code)). An account-scoped key cannot be bound. If the key is stored only at account scope, [supply its value again](/cloud/getting-started/store-a-secret/#2-supply-the-value-without-exposing-it) from your own source under a new name at the application's scope for that environment. The stored value cannot be read back.

A task that names a variable or describes how code reads the key does not, by itself, forbid changing that code ([The rule in code](/cloud/getting-started/store-a-secret/#the-rule-in-code)).

Unless you say otherwise, your AI tool may change your application's own code, but not a library's source. Keeping a variable name does not require keeping the API host.

## What your AI tool does

- Confirms the key's name with `list_secrets`. Where the key is not stored, it follows the `store-key` [skill](/cloud/concepts/glossary/#skill) (`read_context`, id `skill:store-key`).
- Calls `list_outbound_apis`, then declares the upstream with `declare_outbound_api`, or in the [manifest](/cloud/concepts/glossary/#manifest)'s `upstreams` member where the manifest keeps them.
- Calls the upstream through the gateway with the [Egress](/cloud/backend-packages/egress/) package or plain `fetch`, as [step 3](#3-call-it-from-a-route) shows.
- Leaves a provider's own software development kit (SDK) unchanged and declares its upstream with `sdk_settings` ([An unchanged SDK](#an-unchanged-sdk)).
- Offers a run on your machine before the deploy, then deploys and reads `read_status` until the deploy ends.
- Runs `store_secret`, `declare_outbound_api`, `submit_manifest`, and `deploy` with no browser approval. A replacement uses `store_secret` with `replace: true`; `delete_secret` waits for your approval in the browser.
- Ends an upstream only in the order [End an upstream](#end-an-upstream) gives, because `declare_outbound_api` with `remove: true` refuses its calls in both environments.
- Asks you for the name you stored the key under, where the prompt does not say.

## What you need

- The API key, stored on the Turn Zero dashboard. Sign in at turnzero.ai and open **Secrets** → **Add a secret**. Enter a name such as `WEATHER_API_KEY`, paste the key as the value, choose **All apps**, then choose **Save secret**. This account scope lets both development and production use the key.
- The name you gave the key. The value is write-only: nobody can read it back, your AI included.
- For a host that needs no key: the exact hostname in lowercase, or a wildcard domain such as *.example.com.

## Before your AI starts

**For the AI tool:** Check the following before starting.

- A connected, signed-in AI tool ([Connect your AI assistant](/cloud/getting-started/connect-your-tool/)) and an application with a submitted manifest ([Deploy from your computer](/cloud/getting-started/deploy-an-application/)).
- The application's identifier, from `list_applications`.
- The header the service reads its key from, and whether the key takes a prefix such as `Bearer`, from the service's own documentation.

## Steps

### 1. Store the API key

A key stored on the dashboard is already in [custody](/cloud/concepts/glossary/#custody), so your AI tool confirms its name and scope with `list_secrets`, which also lists the settings bound to it. Otherwise it stores the key before `declare_outbound_api`, which refuses a name that is not stored. Choose the route by how the code uses the value, not by the environment variable's name. [Store a secret](/cloud/getting-started/store-a-secret/#the-rule-in-code) explains the rule and the fixed-host exception.

| The value | Its route | Where the value goes |
| --- | --- | --- |
| An API key your code sends to an outside API | `declare_outbound_api`, with `sdk_settings` for an unchanged SDK | It stays at the egress gateway. |
| A value your code uses itself, such as a webhook signing secret | A binding in the manifest's `settings` | It enters your container as a setting. |
| The exception: a key for a client whose host is fixed in code you must not change | A binding in the manifest's `settings`, and the host in `egress` | It enters your container as a setting. |

The gateway uses the key stored for the calling environment, or else the one at account scope. Store one key at account scope when production and development share it, or the same name at each environment's scope when they differ. [Local runs](/cloud/concepts/glossary/#local-run) use the development key. The key never becomes a setting, so code that reads it from `process.env` finds nothing.

### 2. Declare the upstream

Declare only APIs you trust with the stored key. The upstream receives the key and can echo it in its response body; the gateway does not remove such echoes. Use a disposable test value with echo or debugging services, and avoid returning or logging responses that may contain credentials.

Your AI tool calls `declare_outbound_api` with arguments like these, for a weather service that reads its key from the `X-Api-Key` header. `credential_name` is the name the key is stored under.

```json
{
  "name": "weather",
  "base_url": "https://api.weather.example",
  "credential_name": "WEATHER_API_KEY",
  "auth_header": "X-Api-Key",
  "application": "<application id>"
}
```

An upstream's name is unique across your account. Choose a different name if another application already uses it. Two upstreams may use the same `credential_name`.

| Member | Required | What it contains |
| --- | --- | --- |
| `name` | Yes | 1 to 64 letters, digits, hyphens, or underscores, beginning with a letter or digit. |
| `base_url` | Yes | A public HTTPS URL on a host of your own or your provider's, not on an outbound mail port (25, 465, 587, or 2525). |
| `credential_name` | Yes | The name the key is stored under. |
| `auth_header` | Yes | The Hypertext Transfer Protocol (HTTP) header the API reads the key from. |
| `application` | Yes | The one application the upstream belongs to, for good. |
| `auth_format` | No | The header value, containing `{value}`, such as `Bearer {value}`. If omitted, it defaults to `{value}`, which sends the key alone. `list_outbound_apis` returns that default as `"{value}"`. |
| `sdk_settings` | No | The settings an unchanged SDK reads ([An unchanged SDK](#an-unchanged-sdk)). |

For a provider that reads a bearer token, set `auth_header` to `Authorization` and `auth_format` to `Bearer {value}`, as the [OpenAI example](#an-unchanged-sdk) does.

An upstream declared here needs no entry in the manifest's `egress` list ([Egress firewall and request limits](/cloud/concepts/egress-firewall-and-request-limits/#the-https-tunnel)). The gateway dials it from the platform's edge, and the `egress` list names only the hosts the application's own process dials.

The host must resolve to public addresses and must not be one of the platform's own; [How the gateway handles a call](/cloud/concepts/egress-firewall-and-request-limits/#how-the-gateway-handles-a-call) describes both checks.

#### Declare in the manifest

The manifest's optional `upstreams` member declares the same upstream with the code, keyed by its name, each entry taking the members above except `application`. Each `submit_manifest` declares every entry for the application it is submitted for, from that moment. [Author the manifest](/cloud/guides/author-the-manifest/#declare-an-upstream-in-the-manifest) shows the member.

An entry that breaks a rule of this step is refused `manifest_invalid`, at the entry's path. A name another application of your account already uses is refused that way, naming that application. Keep `sdk_settings` with its `key` in an entry whose running copies have a key setting, or the submission ends those keys.

While the member lists an upstream, `declare_outbound_api` refuses to change it, `manifest_owned_field`. Change the entry and resubmit instead. Removing an entry leaves the upstream declared, and `declare_outbound_api` can change it again.

### 3. Call it from a route

The backend calls `/egress/v0/<upstream>/<path>` using `TURNZERO_CLOUD_GATEWAY_URL` as its base address. The platform supplies that setting when it configures a separate gateway origin; otherwise use `TURNZERO_CLOUD_API`. Send `TURNZERO_CLOUD_APP_TOKEN` as the bearer credential. [A deployed app's settings](/cloud/concepts/the-settings-a-deployed-copy-receives/#settings-and-environment-variables-a-deployed-copy-receives) lists these environment variables.

For the Egress package, your AI tool follows [Use the library](/cloud/guides/use-the-library/). The gateway removes your `Authorization` header before adding the stored key, so the upstream never receives your platform credential.

This server responds to `GET /forecast?city=<name>` with the weather service's forecast. Its health path is `/health`. A test runs this sample over the Egress package's test double and checks the forecast, the call it sends, and a refused call.

```js
// src/server.mjs: GET /forecast?city=<name> returns the forecast from the upstream declared as weather.
import { createServer } from 'node:http';
import { EgressClient, GatewayRefusal } from '@turnzero/egress';

// The platform's origin and this copy's credential, from the settings it receives.
const origin = process.env.TURNZERO_CLOUD_GATEWAY_URL ?? process.env.TURNZERO_CLOUD_API;
const transport = (path, init = {}) =>
  fetch(origin + path, { ...init, headers: { ...init.headers, authorization: `Bearer ${process.env.TURNZERO_CLOUD_APP_TOKEN}` } });
const egress = new EgressClient(transport);

const port = Number(process.env.PORT ?? 8080);
createServer(async (req, res) => {
  // A target that does not parse as a URL names no route, so it gets a 404 below.
  let url = null;
  try {
    url = new URL(req.url, 'http://localhost');
  } catch {}
  if (req.method === 'GET' && url?.pathname === '/health') return res.writeHead(200).end('ok');
  if (req.method !== 'GET' || url?.pathname !== '/forecast') return res.writeHead(404).end();
  try {
    // The gateway adds the stored key; the answer is the upstream's own, whatever its status.
    const city = encodeURIComponent(url.searchParams.get('city') ?? '');
    const answer = await egress.call('weather', `/v1/forecast?city=${city}`);
    res.writeHead(answer.status, { 'content-type': 'application/json' }).end(await answer.text());
  } catch (error) {
    // A GatewayRefusal is the gateway's own answer: `error` is the refusal's name, `kind` says what to do.
    console.error(error instanceof GatewayRefusal ? `gateway refused ${error.error} (${error.kind}): ${error.detail}` : error);
    res.writeHead(502).end();
  }
}).listen(port, () => console.log(`listening on ${port}`));
```

If an upstream can echo the key, such as an echo or debugging service, replace the sample's line that returns `answer.text()`. Parse the response and return or log only fields your route needs. For example, for a hypothetical `forecast` field that contains no credentials:

```js
const body = await answer.json();
const result = { forecast: body.forecast };
res.writeHead(answer.status, { 'content-type': 'application/json' })
  .end(JSON.stringify(result));
```

Never return or log the complete response body from an upstream that can echo credentials.

`call` returns the upstream's response whenever it has the marker header `x-egress-upstream`, a 4xx or 5xx included, and throws `GatewayRefusal` for the gateway's own ([Egress](/cloud/backend-packages/egress/#what-it-provides) lists the kinds).

#### Without the Egress package

Plain `fetch` reaches the same upstream with the same path and your platform credential, as the sample's transport does: `fetch(origin + '/egress/v0/weather/v1/forecast?city=Austin', { headers: { authorization: 'Bearer ' + process.env.TURNZERO_CLOUD_APP_TOKEN } })`.

Your code sends no `X-Api-Key` header and holds no key. The gateway removes your `Authorization` header and any header you send under the declared `auth_header` name. It then sets that header itself, here `X-Api-Key: <stored key>`, written in the `auth_format` form.

Every other header you send reaches the upstream unchanged, except the ones the gateway sets again itself, the platform's own, and the ones the edge adds. [What the upstream receives](/cloud/concepts/egress-firewall-and-request-limits/#what-the-upstream-receives) lists each one. A response with the header `x-egress-upstream: weather` is the upstream's own, whatever its status. A response without it is the gateway's refusal, in the platform's error format. A refusal after a stream has begun arrives as an `egress_error` event inside the marked response.

When the upstream answers, the gateway returns its status and body. It removes some response headers and adds `x-egress-upstream` with the upstream's name. [What your code receives](/cloud/concepts/egress-firewall-and-request-limits/#what-your-code-receives) lists the removed headers.

For new code, send the platform credential. Existing code can keep its settings-based bearer route as [Move code that reads the key from an environment variable](#move-code-that-reads-the-key-from-an-environment-variable) explains.

The platform credential fixes the environment. A call under a [minted token](/cloud/concepts/glossary/#minted-token) names it in the header `x-turnzero-cloud-environment`.

### 4. Run it on your machine, then deploy

A [local run](/cloud/guides/run-your-application-on-your-machine/) calls through the gateway under the development credential, so a wrong credential name, header, or key shows up before any deploy. The key must be stored at development or account scope for this.

Then your AI tool deploys as [Deploy from your computer](/cloud/getting-started/deploy-an-application/) describes. Where `read_status` lists the upstream's host under `application.egress`, the code called the host directly, and your AI tool changes that call to the gateway route.

### An unchanged SDK

A provider's own SDK can call through the gateway with no code change. Declare the upstream with `sdk_settings`, naming the settings the SDK reads for its base URL and its key. From the next deploy, promote, or `restart_application`, the deployed copy receives them. The base URL is the gateway's address for the upstream, followed by `base_path` if you set it. Without `base_path`, it ends in `/egress/v0/<upstream>`. The key is an [egress key](/cloud/concepts/glossary/#egress-key) for this upstream and this copy alone, which the gateway swaps for your stored key.

For your own code that keeps this setting, a name such as `WEATHER_EGRESS_KEY` makes clear that it holds an egress key, never the provider's key. Existing code can keep its current name; keep an unchanged SDK's required name.

The OpenAI SDKs read `OPENAI_BASE_URL` and `OPENAI_API_KEY`, and add paths such as `/chat/completions`, so their upstream takes `base_path` `/v1`. The Anthropic SDKs read `ANTHROPIC_BASE_URL`, and send `ANTHROPIC_AUTH_TOKEN` as a bearer. Name that one as `key`, not `ANTHROPIC_API_KEY`, and declare the upstream with `auth_header` `x-api-key`.

The gateway reads an egress key from one header alone: `Authorization: Bearer <key>`, the way both SDKs above send it. A key sent in any other header is not read. Code you write yourself needs no egress key: send your platform credential in that header, as step 3's sample does. Where code without that settings-based bearer route sends the key itself, change it as [Move code that reads the key from an environment variable](#move-code-that-reads-the-key-from-an-environment-variable) shows.

The declaration below is for the OpenAI SDKs.

```json
{
  "name": "openai",
  "base_url": "https://api.openai.com",
  "credential_name": "OPENAI_KEY",
  "auth_header": "Authorization",
  "auth_format": "Bearer {value}",
  "application": "<application id>",
  "sdk_settings": { "base_url": "OPENAI_BASE_URL", "key": "OPENAI_API_KEY", "base_path": "/v1" }
}
```

An egress key works on its own upstream's route alone, and ends with the copy that has it. A revision whose `sdk_settings` is `null`, or has no `key`, ends the upstream's keys in each environment; its `egress_keys_ended` counts them. A settings name the platform sets, or one already in use, is refused `invalid_request`.

The settings reach deployed copies only. For a run on your machine, set them by hand in the environment file the [provision line](/cloud/concepts/turnzero-command/#running-on-your-machine) writes. Set the base URL to that file's `TURNZERO_CLOUD_API`, then `/egress/v0/<upstream>` and `base_path`, and the key to its `TURNZERO_CLOUD_APP_TOKEN`. Never set the key alone: an SDK with no base URL setting sends your development credential to the provider's own host.

### Move code that reads the key from an environment variable

For code that cannot use the settings-based bearer route in [An unchanged SDK](#an-unchanged-sdk), change these three places so the provider's key stays at the gateway:

- Its base URL becomes the gateway's route for the upstream, `<origin>/egress/v0/<upstream>`.
- Its header carries your platform credential, `Authorization: Bearer` with `TURNZERO_CLOUD_APP_TOKEN`, in place of the key.
- It stops reading the key's variable.

For `<origin>`, use `TURNZERO_CLOUD_GATEWAY_URL`, falling back to `TURNZERO_CLOUD_API`, as [step 3 (Call it from a route)](#3-call-it-from-a-route) explains.

First check which stored name the old code uses. A manifest entry such as `"WEATHER_API_KEY": {"secret": "WEATHER_API_KEY"}` binds the stored name in `secret` to the setting on the left. If that stored name is bound in the manifest, a running copy or an operation in flight, declaring an upstream with it is refused `upstream_key_is_bound`.

Keep the old binding while its code still runs. Ask the person to supply the key again from their own source under a new stored name, such as `WEATHER_UPSTREAM_KEY`, following [step 1](#1-store-the-api-key). No call reads back a stored value. Use that new name as `credential_name`; never add it to `settings`. If the stored name was never bound, keep it: the upstream will use it.

For that never-bound key, skip removing the old `settings` entry, the deploy after that removal, and deleting the old stored name. Follow the other steps below, including the first deploy and check, promotion where development is on, `read_status`, and removal of the old host's `egress` entry.

Declare the upstream as [step 2](#2-declare-the-upstream) describes before running the changed code. Keep a matching existing declaration; otherwise call `declare_outbound_api` or, where the manifest keeps upstreams, add the entry below and submit the manifest.

Use `list_outbound_apis` to compare its `application`, `base_url`, `credential_name`, `auth_header`, and `auth_format` with the declaration you need. If it belongs to another application, choose a different upstream name. Otherwise, change any differing member with `declare_outbound_api`, or edit the manifest's entry and resubmit where the manifest keeps it. The example uses `WEATHER_API_KEY`; substitute the new stored name for `credential_name` when moving a bound key.

```json
{
  "upstreams": {
    "weather": {
      "base_url": "https://api.weather.example",
      "credential_name": "WEATHER_API_KEY",
      "auth_header": "X-Api-Key"
    }
  }
}
```

This example uses plain `fetch`. The [Egress package](#3-call-it-from-a-route) calls the same gateway with the same platform credential.

A test runs both halves of this change and checks the address and the headers each sends.

```diff
-const answer = await fetch(`https://api.weather.example/v1/forecast?city=${city}`, {
-  headers: { 'x-api-key': process.env.WEATHER_API_KEY },
-});
+const origin = process.env.TURNZERO_CLOUD_GATEWAY_URL ?? process.env.TURNZERO_CLOUD_API;
+const answer = await fetch(`${origin}/egress/v0/weather/v1/forecast?city=${city}`, {
+  headers: { authorization: `Bearer ${process.env.TURNZERO_CLOUD_APP_TOKEN}` },
+});
```

The gateway sets the `X-Api-Key` header from the stored key named by this declaration. Deploy the changed code, then use `request_route` to call the route that calls the upstream. Where development is on, this checks development; with production alone, the deploy and check are on production.

For a route that requires sign-in, first create a test end user with `add_test_end_users` if needed. Pass its id or label as `request_route`'s `test_end_user` argument, together with `environment` and no `cookie` header. For a route that reads a bearer token, also set `session_as: "bearer"` and leave out the `authorization` header. The platform signs that user in for the call; [Test the signed-in paths](/cloud/guides/test-sign-in-with-test-end-users/#8-test-the-signed-in-paths) gives the steps.

Once the route answers, remove the old `WEATHER_API_KEY` entry from the manifest's `settings`. If no entries remain, leave out the `settings` member; an empty object, `{}`, is also accepted. Keep the old host's `egress` entry for now. Submit the manifest with `submit_manifest`, deploy again, and check the route again. Submitting alone does not remove the setting from a running copy.

Where development is on, ask the person whether to promote the checked version unless they already requested it. With nobody to ask and no prior request, stop and report. After promotion, check the production route. Production's old binding remains until that environment receives the version without it; keep its stored key until then. With production alone, there is nothing to promote.

Call `read_status` for each environment, with `wait_seconds`, until `settled` is true. Read its `summary` to confirm that each environment is serving the version you checked without the old binding. A settled operation can have failed and left the old version serving; do not remove the host or delete the old key in that case. [Read the status](/cloud/getting-started/deploy-an-application/#5-read-the-status) describes the response.

Keep the old host's `egress` entry until no running copy in any environment calls that host directly and no operation in flight can start a copy that does. Then remove the entry if no other direct call needs it, and submit the revised manifest with `submit_manifest`. This removal takes effect for every running copy within about 30 seconds by default while the platform's store answers. During a store outage, the tunnel may keep using a cached entry for up to an hour. The removal needs no deploy. Check the upstream route again in each environment you moved.

Once no running copy or operation in flight uses the old binding, and nothing else needs the old stored name, call `delete_secret` for that name. Ask the person to approve the deletion in the browser. Keep the new stored name: the upstream still uses it.

A provider's SDK you leave unchanged keeps its code, as [An unchanged SDK](#an-unchanged-sdk) describes. Code that already reads its base URL and key from settings and sends the key as `Authorization: Bearer` can use the same route, including through [the manifest's `upstreams` member](/cloud/guides/author-the-manifest/#declare-an-upstream-in-the-manifest). If its key already has a `settings` binding, first store the key again under a new stored name, as above.

Remove the manifest's `settings` entries for the base URL and key that `sdk_settings` will supply. Where the manifest keeps upstreams, add the upstream with the new stored name as `credential_name` and `sdk_settings` naming the settings the code reads, then submit it. Otherwise, submit the manifest without those settings entries, then call `declare_outbound_api` with that declaration. Do not deploy between removing the bindings and declaring the upstream.

The running copy keeps its old values until the deploy. The next copy receives the gateway address and an egress key under the same setting names. Keep the old host's `egress` entry while any running copy still calls that host directly. Deploy, check the route, and follow the promotion, `egress` removal, and old-key deletion steps above. If the key was never bound, use [An unchanged SDK](#an-unchanged-sdk) directly.

#### Keep a key setting with plain fetch

Here is that route for existing code that must keep `WEATHER_API_KEY`. It adds `WEATHER_BASE_URL` and changes the request header from `X-Api-Key` to `Authorization: Bearer`.

Use `WEATHER_UPSTREAM_KEY` for the replacement stored name in the steps above. Remove any manifest `settings` entries for `WEATHER_BASE_URL` and `WEATHER_API_KEY`. Then add this upstream entry and submit the manifest:

```json
{
  "upstreams": {
    "weather": {
      "base_url": "https://api.weather.example",
      "credential_name": "WEATHER_UPSTREAM_KEY",
      "auth_header": "X-Api-Key",
      "sdk_settings": {
        "base_url": "WEATHER_BASE_URL",
        "key": "WEATHER_API_KEY",
        "base_path": "/v1"
      }
    }
  }
}
```

After deploying, `WEATHER_BASE_URL` ends in `/egress/v0/weather/v1`. `WEATHER_API_KEY` holds this copy's egress key, never the provider's key. Change the function to send it as a bearer:

```diff
 export async function forecast(city) {
-  const url = new URL('https://api.weather.example/v1/forecast');
+  const url = new URL(`${process.env.WEATHER_BASE_URL}/forecast`);
   url.searchParams.set('city', city);
   return fetch(url, {
-    headers: { 'x-api-key': process.env.WEATHER_API_KEY },
+    headers: { authorization: `Bearer ${process.env.WEATHER_API_KEY}` },
   });
 }
```

The gateway replaces that bearer with the stored provider key in `X-Api-Key`. Sending the egress key in `x-api-key` instead is refused; it is read only from `Authorization: Bearer`.

For a local run, set both values as [An unchanged SDK](#an-unchanged-sdk) describes. Follow the migration's deploy checks, promotion, host removal and old-key deletion steps above.

A rollback to an older version does not restore a binding whose setting name the upstream now supplies.

### Rotate the key

Replace the key with its issuer, then call `store_secret` with `replace: true` under the same name, application, and environment, and run the command line it returns. The gateway reads the key on every call, so the next call uses the new key, with no redeploy. `list_secrets` gives the name's `rotated_at`.

`list_secrets` also gives the stored value's `fingerprint`, a short keyed code. Read the row for the application and environment you rotated. The gateway's next call reads that stored value; it keeps no copy. A value with no recorded fingerprint reads `null`. The fingerprint identifies the stored value without exposing it; the request below checks that the new key works. [Store a secret](/cloud/getting-started/store-a-secret/#check-that-a-rotation-reached-the-running-copy) explains fingerprints.

To check the new key, your AI tool can call an application route that uses this upstream with `request_route`, naming the environment where the key was rotated. Use `test_end_user` if the route requires sign-in, as [Test the signed-in paths](/cloud/guides/test-sign-in-with-test-end-users/#8-test-the-signed-in-paths) describes. Check that the upstream call succeeds; a health response alone does not prove the key works.

Alternatively, call the upstream through the gateway under a minted token, as step 3 describes, and read the upstream's answer. A changed `declare_outbound_api` takes effect after the credential interval that [Sign-in, sessions, and tokens](/cloud/concepts/sign-in-sessions-and-tokens/) gives.

### End an upstream

Call `declare_outbound_api` with the upstream's `name` and `remove: true` to end it. The declaration is removed, and the name is free for a new one. 

While the platform's store answers, calls to the upstream are refused in both environments within about 30 seconds by default. Its egress keys stop working too. During a store outage, a gateway may keep using its cached declaration for up to an hour. The refusal applies to calls from any running copy that still calls the upstream, whether or not that copy held a key.

The response's `egress_keys_ended` counts those keys, and `detail` lists the environments whose copies lost one. The stored key stays in custody, and `delete_secret` can then delete it where nothing else uses it. A call that fails ends nothing, and calling again ends the upstream.

Only this call, or deleting the application or your account, ends an upstream. Submitting a manifest without the entry leaves it declared, so a running version that still calls it keeps working. While the manifest lists the upstream, this call is refused `manifest_owned_field`. So end one in this order: remove the entry and submit the manifest, then deploy and promote the version that no longer calls the upstream, then call `declare_outbound_api` with `remove: true`.

A name that is not declared returns `unchanged`. To bring an ended upstream back, declare it again with `declare_outbound_api`, then deploy or promote each environment so its copies get fresh settings and keys.

### A host that needs no key

A host the application reaches with no stored key goes in the manifest's `egress` list: a public data feed, a webhook target, or a provider whose key the end user sends. The application reaches it through the [HTTPS tunnel](/cloud/concepts/glossary/#https-tunnel) with a client the tunnel covers, such as the runtime's global `fetch`. [Egress firewall and request limits](/cloud/concepts/egress-firewall-and-request-limits/) lists the covered clients, the observe and enforce modes, and the records `read_logs` returns with `source: "egress"`.

### Mail from the backend

Any application can send an occasional request or notice, such as an order confirmation, through the platform's email service, with no provider or key of its own ([Send email from your application](/cloud/guides/send-email-from-your-application/)). The service counts each application's recipients by the hour and the day.

For more mail than its counts allow, or for mail it does not send, such as newsletters or attachments, use your own mail provider. Declare its HTTPS API as an upstream and call it as shown above. The outbound mail ports stay refused on both routes.

### The platform's own upstreams

Two upstreams are the platform's, and the application declares neither. [Call an AI model](/cloud/guides/call-an-ai-model-under-the-allowance/) calls `ai-allowance`, on a key the platform keeps. [Issue Tracking](/cloud/backend-packages/tztrack/) calls `issue-tracking`, the route to the application's own [issue-tracking space](/cloud/concepts/glossary/#issue-tracking-space), at the `report` [grant level](/cloud/concepts/glossary/#grant-level).

## Expected result

- `declare_outbound_api` returns the `upstream` with `outcome` `created` or `revised`. Where the key is stored for one environment alone, its `detail` names the other, whose calls are refused until it has a key. Its `page` is this page's address.
- A `submit_manifest` whose `upstreams` member names the upstream returns `upstreams` rows, one per upstream and environment, each saying whether its key is `stored` there. A deploy whose environment lacks a key lists the upstream in its version's `outcome.credentials_missing`. Its `next` lists the `store_secret` call for a key not stored yet.
- `GET /forecast?city=Austin` responds with the upstream's status and body. The gateway's response to the backend had the header `x-egress-upstream: weather`, and the application's process never had the key.
- `declare_outbound_api` with `remove: true` returns the `upstream` as it was before the removal, `outcome` `removed`, and `egress_keys_ended`. A name not declared returns `outcome` `unchanged` and `upstream` `null`.

## Refusals

See the [refusals reference](/cloud/reference/refusals/) for other platform errors.

A gateway refusal has no `x-egress-upstream` header. [Call an AI model](/cloud/guides/call-an-ai-model-under-the-allowance/#refusals) lists the allowance route's refusals, and [Egress firewall and request limits](/cloud/concepts/egress-firewall-and-request-limits/) the tunnel's.

| Refusal | Status | Cause | Remedy |
| --- | --- | --- | --- |
| `credential_not_in_custody` | 409 | The `credential_name` is not stored at a scope the upstream can use. At a call, `detail` says when it is stored for the other environment alone. | Store the key under that name with `store_secret`, at this environment's scope or at account scope, then retry. |
| `upstream_key_is_bound` | 409 | A setting binds the credential: in the manifest's `settings`, in the running copy of either environment, or in a deploy, promote, or redeploy in flight to one. The `detail` names the setting and where it is bound. | Store the key under another name and declare with it. Or remove the binding, resubmit, deploy or promote each environment whose running copy has it, and declare again. |
| `name_bound_to_realm` | 409 | The name is stored for a realm's work-account client secret or Sign in with Apple key. | Store the upstream's key under another name and declare with that name. |
| `binding_refused` | 409 | Another application in your account already uses that upstream name. | Choose a name it does not use. |
| `manifest_owned_field` | 409 | `declare_outbound_api` would change an upstream the application's manifest lists in `upstreams`; `detail` lists each field. Or a call with `remove: true` would end one. | Change the entry in the manifest and resubmit it with `submit_manifest`. To end the upstream, remove the entry, resubmit, and promote the version that no longer calls it, then call `declare_outbound_api` with `remove: true` again. |
| `refused_platform_host` | 400 | The base URL's host is one of the platform's own. | Declare the upstream against a host of your own. |
| `undeclared_upstream` | 404 | Your account declares no upstream by that name. | Declare it, or call the name you declared. |
| `environment_required` | 400 | A call under a minted token or an account-wide credential had no `x-turnzero-cloud-environment` header. | Send the header, or call under the platform credential. |
| `egress_key_not_admitted` | 403 | An egress key was sent anywhere but its own upstream's route. | Send it only under the base URL its setting names. |
| `refused_base_url` | 400 | At the call, the declared base URL's scheme, host, port, or address type is refused. | Declare the upstream again with a public HTTPS base URL. Omitting `sdk_settings` from that declaration keeps them. A base URL on a mail port (25, 465, 587, or 2525) stays refused. Send mail through a mail provider's HTTPS API instead, declared as an upstream. |
| `egress_private_address`, `egress_loopback_address`, `egress_link_local_address`, `egress_reserved_address`, `egress_platform_address` | 403 | The host resolved to a non-public address of that type. | Declare the upstream with a host that resolves to public addresses only. |
| `upstream_unreachable` | 502 | The connection to the upstream failed; `detail` gives the error code. | Retry, and check the base URL and the upstream's own status. |
| `egress_connections_capped` | 429 | The application opened more tunnel connections in this UTC minute than its limit allows. | Wait for the next minute or reuse connections. |
| `egress_daily_bytes_capped` | 429 | The application passed its outbound bytes limit for the UTC day. The body includes `count`, `limit`, and `resets_at`. | Wait for `resets_at`. |

## Related

- [Store a secret](/cloud/getting-started/store-a-secret/) supplies the key without exposing it.
- [Egress](/cloud/backend-packages/egress/) describes the client, its refusal kinds, and the reader for a streamed answer.
- [Egress firewall and request limits](/cloud/concepts/egress-firewall-and-request-limits/) describes how the gateway handles a call, the tunnel, and the outbound limits.
- [Author the manifest](/cloud/guides/author-the-manifest/) edits the `egress` list and the `upstreams` member.
- [Send email from your application](/cloud/guides/send-email-from-your-application/) sends an occasional email with no provider of your own.
- [declare_outbound_api](/cloud/reference/actions/declare-outbound-api/) and [list_outbound_apis](/cloud/reference/actions/list-outbound-apis/) give each action's arguments and result.
