---
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."

Store the provider's key on the dashboard or through your AI assistant ([step 1](#1-store-the-api-key)), then declare the upstream ([step 2](#2-declare-the-upstream)). When your route calls the gateway, the gateway adds the stored key to its request to the upstream ([step 3](#3-call-it-from-a-route)). It leaves the provider's key out of your app's settings. The upstream can still return the key in its response, in the body or in any header other than the one the key was sent in.

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 assistant 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 API key from an environment variable](/cloud/guides/use-an-api-key-from-an-environment-variable/) gives the short steps to move the call to the gateway, keep the variable names, or bind the key for a direct call. If your code uses a custom header and you can change the request but must keep the key's variable name, see the [plain fetch example](#keep-a-key-setting-with-plain-fetch).

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 when the person requires the client's fixed host unchanged, or library source fixes it with no configurable gateway address. [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, call the API through its gateway route. If the manifest lists the upstream, edit that entry and submit the manifest. Otherwise, use `declare_outbound_api`. Send `TURNZERO_CLOUD_APP_TOKEN` as a bearer and remove the code that reads 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)).
- **The binding exception:** the person requires the client's fixed host unchanged, or library source fixes it with no configurable gateway address. 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 assistant 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 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 in the [manifest](/cloud/concepts/glossary/#manifest)'s `upstreams` member where the manifest carries it. Otherwise, calls `declare_outbound_api`.
- 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 assistant:** Check the following before starting.

- A connected, signed-in AI assistant ([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 assistant 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.

If the key is missing, `declare_outbound_api` returns `credential_not_in_custody`. If only one environment can use the stored key, the action tells you which one.

To supply a key from your password manager, [run the returned command in your own terminal](/cloud/guides/supply-a-secret-value-without-exposing-it/#type-the-value-in-your-own-terminal). Paste the value at its hidden prompt and press Enter.

| The value | Its route | Where the value goes |
| --- | --- | --- |
| An API key your code sends to an outside API | The manifest’s `upstreams` entry, or `declare_outbound_api` for an upstream outside the manifest. Use `sdk_settings` for an unchanged SDK. | The gateway sends the key to the API without putting it in the app's settings. The response can carry it back in the body or in any header other than the one the key was sent in. |
| 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: an API key where the person requires the client's fixed host unchanged, or library source fixes it with no configurable gateway address | 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 the response body or in a response header. The gateway removes the header the key was sent in. Other headers the gateway forwards can still contain the key. Use a disposable test value with echo or debugging services, and avoid returning or logging responses that may contain credentials.

Your AI assistant 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}"`. |
| `token_shape` | No | How the gateway reads token counts from responses. Use `gemini` or `anthropic` for the matching response format. Leave it out if the upstream reports no token counts. |
| `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 platform's gateway connects to this API on your app's behalf. List only the hosts your application process connects to directly in `egress`.

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. Include the required and optional declaration fields above. The manifest key supplies `name`, and the submission supplies `application`. Use the separate action to remove the declaration. 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.

You can submit an `upstreams` entry before storing its key. The app can deploy and serve, with `outcome.credentials_missing` listing the upstreams that still need keys. The gateway refuses calls to those upstreams until you store their keys.

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 both `sdk_settings` and its `key` in the entry while a running copy uses that key setting. If you omit either one from a submission, those keys stop working.

While the manifest lists an upstream, `declare_outbound_api` returns `manifest_owned_field` if you try to change it. 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.

The gateway removes one trailing slash from the upstream’s declared `base_url`, then appends the path and query string after `/egress/v0/<upstream>`. For `base_url` `https://api.weather.example/service/`, the path `/egress/v0/weather/v1/forecast?city=Austin` goes to `https://api.weather.example/service/v1/forecast?city=Austin`. Percent-encoded path segments stay encoded.

The gateway forwards ordinary headers such as `Content-Type`. It removes the caller’s platform authorization and platform session cookies, and replaces the declared authentication header with the stored key. When absent, it supplies defaults for `Accept`, `Accept-Language`, `User-Agent`, and `Sec-Fetch-Mode`.

[What the upstream receives](/cloud/concepts/egress-firewall-and-request-limits/#what-the-upstream-receives) lists the transport and forwarding headers the gateway strips. For the Egress package, your AI assistant follows [Use the feature package library](/cloud/guides/use-the-library/).

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 or headers 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 } })`.

With `auth_header: "X-Api-Key"`, the gateway sets `X-Api-Key` to the stored key in the declared `auth_format`. If your code sends `x-api-key` anyway, the gateway replaces it. Header names match regardless of case. The `Authorization` you send authenticates your call to Turn Zero. The gateway removes it before adding the upstream key.

Send the headers the upstream needs, such as `Content-Type`, a provider version header, or `Idempotency-Key`. The gateway passes them through unless a removal rule applies. [What the upstream receives](/cloud/concepts/egress-firewall-and-request-limits/#what-the-upstream-receives) lists the request headers the gateway removes or sets itself.

The gateway marks its upstream response with `x-egress-upstream: weather`, whatever the status. It passes redirects back to your client. If your client follows a redirect, the later response may have no marker. An error after a stream has begun can arrive 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.

If a local or deployed check makes a paid call with a stored key, make that call only if the person requested it in this run.

Then your AI assistant deploys as [Deploy from your computer](/cloud/getting-started/deploy-an-application/) describes. Exercise the route that makes the upstream request and check the provider response. Then check `application.egress.read` in the full `read_status` reply. An empty list can accompany `skipped`, `unavailable`, or `withheld`. If `application.egress.undeclared` lists the host, confirm which application route made that connection before changing it to the gateway route. The list covers recent recorded connections, so it does not show a function call refused before connecting.

### 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.

Use valid, distinct setting names for `base_url` and `key`. If you include `base_path`, use a path such as `/v1` of at most 200 characters, with no host, query, or fragment.

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. The gateway sends the provider's key to the upstream without putting the key in the app's settings. The upstream can still return it in the response, in the body or in any header other than the one the key was sent in.

- 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, where the manifest keeps upstreams, add the entry below and submit the manifest, or else call `declare_outbound_api`.

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, edit the manifest's entry and resubmit where the manifest keeps it, or else change any differing member with `declare_outbound_api`. 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 check the upstream call. Make a paid call with a stored key only if the person requested it in this run. 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` for the same name and scope. If the key is stored for one environment, give that application and environment. If it is stored for the account, use account scope. Run the returned command when the call gives you one. 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`. [Rotate a stored secret](/cloud/guides/rotate-a-stored-secret/#3-check-an-upstream-key) shows what to check after the replacement.

`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.

For either rotation check below, make a paid call with a stored key only if the person requested it in this run.

To check the new key, your AI assistant 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. Name the environment in `x-turnzero-cloud-environment` 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. 

When the platform can read the upstream settings from its store, it refuses calls to the upstream 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. Use `delete_secret` if nothing else uses it.

If you cannot tell whether the removal succeeded, use `list_outbound_apis` to check the declaration first. Repeat the removal only if the same declaration is still there. A new declaration can reuse the name.

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, the removal is refused `manifest_owned_field`. Remove the entry and submit the manifest. Deploy the version that no longer calls the upstream. If the application has development, promote that version to production. Once the new code is serving in each environment, 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/) 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 marks its response `x-egress-upstream: weather` and leaves the provider's key out of the app's settings. The app can receive the key if the upstream echoes it in the body or in any header other than the one the key was sent in.
- `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 before the response starts has no `x-egress-upstream` header. If an error cuts off a marked stream, its last event can be `egress_error`.

The keyed gateway's default limits are 8 MiB for the request body, 32 MiB for the upstream response body and 120 seconds for the upstream call. For a stream, the time limit covers the whole stream. A stream that hits a limit ends early. Its final event can name the error, and the HTTP status already sent stays the same.

[Call an AI model](/cloud/guides/call-an-ai-model/#refusals) lists the allowance route's refusals. [Egress firewall and request limits](/cloud/concepts/egress-firewall-and-request-limits/) covers the keyed gateway and the tunnel.

| 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. |
| `credential_unreadable` | 502 | The gateway found the stored name but could not read its value. | The gateway stopped before calling the upstream, so you can retry. If the refusal persists, ask the app owner to check the name and scope and report the read failure. If the value needs replacement, use `store_secret` with a private local file or let the owner enter it in their own terminal. Keep the value out of chat, command output and reports. |
| `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 used for a realm's work-account client secret, OpenID Connect client secret, or Apple sign-in key. | Store the upstream's key under another name and declare with that name. |
| `name_bound_to_push` | 409 | The name is used for a push provider's credential. | 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 and resubmit it with `submit_manifest`. To end the upstream, first remove the entry and resubmit. Follow [End an upstream](#end-an-upstream) to deploy and, where needed, promote the version that no longer calls it before calling `declare_outbound_api` with `remove: true` again. |
| `refused_platform_host` | 400 | The base URL's host is one of the platform's own. | Choose a base URL on a host you control. If the manifest lists the upstream, update its `upstreams` entry, submit the manifest with `submit_manifest`, then deploy. Otherwise, resubmit `declare_outbound_api` under the same name. Give a platform-managed upstream refusal to the platform operator. |
| `undeclared_upstream` | 404 | Your account declares no upstream by that name. | If the detail rejects the name itself, correct it in the request. Check the name with `list_outbound_apis`. If it is absent, use `declare_outbound_api` before sending the request again. |
| `environment_required` | 400 | A call under a minted token or an account-wide credential had no valid `x-turnzero-cloud-environment` header. | Send the header with the intended environment, or call under that environment's platform credential. |
| `environment_mismatch` | 403 | The header names a different environment from the one fixed by the credential. | Omit the header or make it match the credential's environment. |
| `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. | Call a declared platform service directly without a proxy. Use a hostname and redirect targets that resolve only to public unicast addresses outside the platform range. If the manifest owns the upstream, update its `upstreams` entry, submit the manifest with `submit_manifest`, then deploy. Otherwise, run `declare_outbound_api` under the same name. Give a platform-managed upstream refusal to the platform operator. |
| `upstream_unreachable` | 502 | The gateway could not reach the upstream or finish reading its response. The `detail` gives the error code. | Check the base URL and the upstream’s status. If resolution fails, correct the destination you manage or report a platform-managed origin. For other transport errors, the upstream may have acted before its response was lost. Retry a read if needed. For a write, retry only after confirming it had no effect or by reusing the same idempotency key where the upstream supports it. Treat a cut-off stream, including one that ends with `egress_error`, as incomplete. |
| `request_too_large` | 413 | The request body exceeds the gateway's limit. | Send a smaller request. |
| `response_too_large` | 502 | The upstream response is too large to send as a whole. | Ask for less data at once. Use paging if the upstream offers it. |
| `upstream_timeout` | 504 | The upstream took too long before the gateway could send its response. | Retry a read if needed. For a write, retry only after confirming that it had no effect or by reusing the same idempotency key where the upstream supports it. |
| `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.
