# Python

Source: https://prontaro.com/docs/languages/python/

Connect Python services to your dedicated static IPv4 using requests, sync or async httpx, and aiohttp with persistent connection pooling.

All three HTTP clients accept the same Prontaro proxy credentials out of the box; only `socks5h://` requires installing a small extra package:

| Library | Proxy schemes | Extra package for `socks5h://` |
| --- | --- | --- |
| `requests` | `https://`, `http://`, `socks5h://` | `PySocks` (or `requests[socks]`) |
| `httpx` (sync / async) | `https://`, `http://`, `socks5h://` | `httpx[socks]` |
| `aiohttp` | `https://`, `http://`, `socks5h://` | `aiohttp-socks` |

## Step 1. Get your proxy URL

1. Open **IP addresses** in your Prontaro dashboard ([my.prontaro.com/ips](https://my.prontaro.com/ips)) and select your IPv4.
2. Copy the `HTTPS` (`:443`) or `SOCKS5` (`:1080`) URL under **Proxy credentials**.

IP addresses Proxy credentials [Open in dashboard](https://my.prontaro.com/ips)

Export the proxy string to `PRONTARO_PROXY_URL`:

```bash
export PRONTARO_PROXY_URL="https://user:pass@<entry>.prontaro.io:443"
```

## `requests` with `PySocks`

Install `requests` together with `PySocks` so you can switch between `https://` and `socks5h://` without touching your code:

```bash
python3 -m pip install requests PySocks
```

Reuse a single `requests.Session()` to preserve keep-alive connections:

```python
# check_requests.py
import os
import requests

proxy_url = os.environ["PRONTARO_PROXY_URL"]

session = requests.Session()
session.trust_env = False  # ignore global HTTP_PROXY; use the explicit URL only
session.proxies.update({
    "http": proxy_url,
    "https": proxy_url,
})

response = session.get("https://api.ipify.org", timeout=(5, 15))
response.raise_for_status()
print(response.text.strip())
```

Verify your outbound IP:

```
 
203.0.113.10
```

To switch to SOCKS5, change `PRONTARO_PROXY_URL` to `socks5h://user:pass@<entry>.prontaro.io:1080` — with `PySocks` installed, no code changes are required.

Once `api.ipify.org` returns your dedicated IPv4, you can restrict destinations in the dashboard (**IP addresses → Proxy credentials → Access**).

## `httpx` (sync and async) + `[socks]`

`httpx` supports `https://`, `http://`, and `socks5h://` through the single `proxy=` parameter:

```bash
python3 -m pip install "httpx[socks]"
```

Synchronous client (`httpx.Client`):

```python
# check_httpx.py
import os
import httpx

proxy_url = os.environ["PRONTARO_PROXY_URL"]

with httpx.Client(
    proxy=proxy_url,
    timeout=httpx.Timeout(15.0, connect=5.0),
    limits=httpx.Limits(max_connections=20, max_keepalive_connections=10),
) as client:
    response = client.get("https://api.ipify.org")
    response.raise_for_status()
    print(response.text.strip())
```

Asynchronous client (`httpx.AsyncClient`):

```python
# check_httpx_async.py
import asyncio
import os
import httpx

async def main() -> None:
    proxy_url = os.environ["PRONTARO_PROXY_URL"]
    async with httpx.AsyncClient(
        proxy=proxy_url,
        timeout=httpx.Timeout(15.0, connect=5.0),
    ) as client:
        response = await client.get("https://api.ipify.org")
        response.raise_for_status()
        print(response.text.strip())

asyncio.run(main())
```

In FastAPI, Starlette, or background workers, initialize one shared `httpx.AsyncClient` in your application lifespan and close it on shutdown instead of opening a new client per request.

## `aiohttp` and `aiohttp-socks`

`aiohttp` (>= 3.10) accepts HTTP/HTTPS proxies via `proxy=`, while `socks5h://` requires `ProxyConnector` from `aiohttp-socks`:

```bash
python3 -m pip install aiohttp aiohttp-socks
```

```python
# check_aiohttp.py
import asyncio
import os
import aiohttp
from aiohttp_socks import ProxyConnector

async def via_http_proxy() -> None:
    timeout = aiohttp.ClientTimeout(total=15, connect=5)
    async with aiohttp.ClientSession(timeout=timeout) as session:
        async with session.get(
            "https://api.ipify.org",
            proxy=os.environ["PRONTARO_PROXY_URL"],
        ) as response:
            response.raise_for_status()
            print("HTTPS proxy:", (await response.text()).strip())

async def via_socks5h() -> None:
    # socks5h:// enables remote DNS resolution (rdns=True) automatically
    connector = ProxyConnector.from_url(os.environ["PRONTARO_SOCKS_URL"])
    timeout = aiohttp.ClientTimeout(total=15, connect=5)
    async with aiohttp.ClientSession(connector=connector, timeout=timeout) as session:
        async with session.get("https://api.ipify.org") as response:
            response.raise_for_status()
            print("SOCKS5h:", (await response.text()).strip())

asyncio.run(via_http_proxy())
```

## Environment variables: `HTTP_PROXY`, `HTTPS_PROXY`, and `NO_PROXY`

`requests` and `httpx` read `HTTPS_PROXY`, `HTTP_PROXY`, and `NO_PROXY` automatically. By contrast, `aiohttp` ignores environment variables unless you pass `ClientSession(trust_env=True)`.

```bash
export HTTPS_PROXY="$PRONTARO_PROXY_URL"
export NO_PROXY="localhost,127.0.0.1,::1,169.254.169.254,.internal"
```

In services that talk to both internal microservices and allowlisted partner APIs, pass `PRONTARO_PROXY_URL` explicitly to a dedicated client instead of setting a process-wide `HTTPS_PROXY`.

## Common Python issues

> **httpx >= 0.28 removed the proxies= argument**
>
> Older snippets use `httpx.Client(proxies=...)`, which raises `TypeError` in current `httpx` releases. Always use the singular form: `proxy=os.environ["PRONTARO_PROXY_URL"]`.

- **`Missing dependencies for SOCKS support`.** Base HTTP clients do not bundle SOCKS5 drivers — install `PySocks` (for `requests`), `httpx[socks]` (for `httpx`), or `aiohttp-socks` (for `aiohttp`).
- **`socks5://` instead of `socks5h://`.** Without `h`, DNS resolves locally on your host and sends an IPv4 address instead of the hostname, so domain rules in your **To** allowlist reject the connection.
- **Top-level `requests.get()` or `httpx.get()` in loops.** One-shot calls drop keep-alive and can exhaust [concurrent connection limits](https://prontaro.com/docs/billing/limits.md). Reuse `Session` / `Client` / `AsyncClient`.
- **Older `urllib3` or `aiohttp` with `https://` proxies.** Upgrade your dependencies, or fall back to `http://user:pass@<entry>.prontaro.io:8080` (target HTTPS remains end-to-end encrypted).

## Calling an API through a Relay URL

If a third-party SDK does not expose proxy settings, create a Relay in the dashboard ([IP addresses](https://my.prontaro.com/ips)) and swap only the base URL:

```python
import os
import httpx

headers = {
    "Authorization": f"Bearer {os.environ['PARTNER_API_TOKEN']}",
    # Include only if you enabled a password (in the dashboard under IP addresses → Relay address → Access):
    "Prontaro-Relay-Auth": f"{os.environ['RELAY_LOGIN']}:{os.environ['RELAY_PASSWORD']}",
}

response = httpx.get(
    f"{os.environ['PRONTARO_RELAY_URL']}/v1/status",
    headers=headers,
    timeout=15.0,
)
response.raise_for_status()
print(response.json())
```

See [Relay URLs](https://prontaro.com/docs/outbound/relay.md) for TLS termination details and limits.

## Next steps

- [curl and environment variables](https://prontaro.com/docs/languages/curl.md) — diagnose `407` and `403` errors with `curl -v`.
- [HTTP & SOCKS5 proxy](https://prontaro.com/docs/outbound/proxy.md) — configure `access` and `targets` allowlists and credential rotation.
- [Go](https://prontaro.com/docs/languages/go.md) — configure `net/http` and `golang.org/x/net/proxy`.
