# Private links API

This API reads the proxy settings of the gateway and sends the HTTP requests of a program through
the proxy. The proxy opens company hosts that only the gateway computer can reach.

The examples use the [Python SDK](python-sdk.md). To see the same steps as [HTTP API](http-api.md)
requests, select **HTTP** at the top of the page.

## When to use

- **A script must read a company host that only the gateway reaches.** [Send a request through the
  proxy](#send-a-request-through-the-proxy).
- **A tool must know if the gateway opens a link.** [Check a link](#check-a-link).
- **A client must show the proxy settings.** [Read the proxy settings](#read-the-proxy-settings).

To turn on the proxy and choose the domains, read [Private links](private-links.md).

## Before you start

Connect a `GatewayClient` with the gateway token, as in [Connect to a gateway and run a
task](python-sdk.md#connect-to-a-gateway-and-run-a-task). The examples use `client`. A client
without a token raises `ValueError`, because the proxy needs the token.

## Operations

| Task | Typed call | Generated method |
|---|---|---|
| Read the proxy settings | `client.proxy()` | `client.routes.get_proxy()` |
| Check a link | `proxy.covers(link)` | None |
| Get the proxy URL for a link | `proxy.proxy_for(link)` | None |
| Send requests through the proxy | `proxy.opener()` | None |

## Read the proxy settings

```python
proxy = client.proxy()
if proxy is None:
    print("The proxy is off.")
else:
    print(proxy.host, proxy.port, proxy.allowed_domains, proxy.denied_domains, proxy.ports)
```

`client.proxy()` returns a `GatewayProxy` object, or `None` when the proxy is off. `host` is the
host of the client URL. Each call reads the settings again, so a change shows at once. The text of
a `GatewayProxy` object does not show the token.

## Check a link

```python
link = "https://grafana.acme.io/d/latency"
print(proxy.covers(link))
```

`covers(link)` returns `True` when the proxy opens the link. It uses the same rules as the gateway.

## Send a request through the proxy

```python
link = "https://wiki.corp.internal/start"
with proxy.opener().open(link) as answer:
    print(answer.status, answer.read()[:200])
```

`opener()` returns a `urllib` opener. It sends the links that the proxy opens through the proxy
and opens other links directly. It checks a redirect again, so the token never goes to a host that
is not on the list.

With another HTTP library, give the proxy URL of each link:

```python
import httpx

response = httpx.get(link, proxy=proxy.proxy_for(link))
```

`proxy_for(link)` returns `None` for a link that the proxy does not open. The proxy URL has the
token, so keep the URL out of logs.

## See also

- To turn on the proxy and open private links in the Companion app, read [Private
  links](private-links.md).
- To find other gateway requests, read [HTTP API](http-api.md).
