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

# Python SDK

> Install the Python SDK and use it by task: create sandboxes, run and stream commands, move files, serve apps, use snapshots and browsers, work with asyncio, handle errors, and make any API call.

The Python SDK, `fibre-sdk`, lets you work with sandboxes as objects in your code. It reads your API key from the
environment, gives you command output as it is written, retries temporary failures safely, and turns errors into
typed exceptions. It runs on **Python 3.11 or later**, has a regular API and an `asyncio` one with the same
methods, and depends only on `httpx2`.

This page is organised by task. Each section shows a short example and links to the guide that explains the
feature in depth. At the end you will find a table of every method.

## Install and configure

Add the SDK to your project and make your API key available:

```bash title="Terminal" norun reason="installs into your own project" theme={null}
pip install fibre-sdk
export FIBRE_API_KEY="fb_live_…"
```

The package is called `fibre-sdk`, and you import it as `fibre`. For most programs, that is all the setup needed.
Calls such as `Sandbox.create()` automatically use a client built from `FIBRE_API_KEY` (and from `FIBRE_API_URL`,
which defaults to `https://api.fibre.dev`).

If you need different settings, for example a different key, create a `Fibre` client yourself and pass it as
`client=`:

```python title="Python" norun reason="shows the client options" theme={null}
import os

from fibre import Fibre, Sandbox

fibre = Fibre(
    api_key=os.environ["MY_KEY"],  # FIBRE_API_KEY by default
    timeout=60,  # seconds per request (streams are not limited)
    max_retries=2,  # on dropped connections, 429, 502, 503, 504
)
sbx = Sandbox.create(size="small", client=fibre)
```

## Create, run, delete

The basic flow is to create a sandbox, run something in it and read the result:

```python title="Python" run theme={null}
from fibre import Fibre, NotFoundError, Sandbox, Secret, Snapshot

sbx = Sandbox.create(size="small", lifetime=900, idle_timeout=120, labels={"docs": "sdk", "user": "42"})

r = sbx.run("python3 -c 'print(2 ** 10)'")
print(r.exit_code, r.stdout)  # 0 1024
```

* **A command can be a string or a list.** A string runs through the shell (`sh -c`), so pipes and `&&` work. A
  list is the program followed by its arguments.
* **`run()` waits for the command to finish**, with no time limit unless you pass `timeout=`. A non-zero exit code
  is returned as a result, not raised as an error.
* **`cwd` and `env`** set the directory and the environment variables for that one command.
* **Durations are in seconds** everywhere: `lifetime`, `idle_timeout`, `timeout`.

When a sandbox is only needed for a block of code, use it in a `with` statement and it is deleted at the end, even
if the code raises:

```python title="Python" run theme={null}
with Sandbox.create(lifetime=300, labels={"docs": "sdk"}) as scratch:
    print(scratch.run("uname -s").stdout)  # Linux
```

Read more in [create and configure](https://docs.fibre.dev/sandboxes/overview.md).

## Stream output as it happens

For longer commands, `spawn()` starts the command in the background and returns straight away. You can then read
its output with `output()`, piece by piece, as the command writes it:

```python title="Python" run theme={null}
build = sbx.spawn("for i in 1 2 3; do echo step $i; sleep 1; done")
for chunk in build.output():
    print(chunk.data, end="")  # step 1 … step 2 … step 3
done = build.wait()
print(done.exit_code)  # 0
```

`chunk.stream` tells you whether a piece came from `stdout` or `stderr`. `chunk.data` is text, and `chunk.raw` holds
the exact bytes, for programs that write binary output. If the connection drops, `output()` reconnects and
continues from where it left off.

## Run a server in the background

A server should keep running after the call that started it, and through sleep and wake. Start it with
`keep=True`:

```python title="Python" run theme={null}
server = sbx.spawn(["python3", "-m", "http.server", "8000"], keep=True)
print(server.status, server.pid)  # detached 23
server.kill()
```

## Write to a program's input

Start a command with `stdin=True` to send it input while it runs:

```python title="Python" run theme={null}
py = sbx.spawn(["python3", "-u", "-i", "-q"], stdin=True)
py.write("print(sum(range(100)))\n")
py.close_stdin()
print(py.wait().stdout)  # 4950
```

Read more in [run commands](https://docs.fibre.dev/sandboxes/running-commands.md).

## Files

Every sandbox has a `files` property for reading and writing its files directly:

```python title="Python" run theme={null}
import json

sbx.files.write("/work/data.json", json.dumps({"hello": "world"}))
print(json.loads(sbx.files.read("/work/data.json")))  # {'hello': 'world'}

print([e["name"] for e in sbx.files.list("/work")["entries"]])  # ['data.json']

data = sbx.files.read_bytes("/work/data.json")  # bytes, for binary files
sbx.files.remove("/work", recursive=True)
```

`write()` accepts text or bytes. Read more in [files](https://docs.fibre.dev/sandboxes/files.md).

## Find sandboxes again

List sandboxes by their labels, get one by its ID, and change what can change:

```python title="Python" run theme={null}
for s in Sandbox.list(labels={"user": "42"}):
    print(s.id, s.status)

same = Sandbox.get(sbx.id)
same.update(lifetime=1800, labels={"docs": "sdk", "user": "42", "state": "active"})
print(same.expires_at, same.labels["state"])  # 2026-… active
```

## Serve an app

Create the sandbox with `exposed_port`, start a server on that port, and it is available at the sandbox's `url`:

```python title="Python" norun reason="the public URLs page runs the same calls" theme={null}
app = Sandbox.create(exposed_port=3000)
app.spawn(["node", "server.js"], keep=True)
print(app.url)  # https://sbx-….fibre.run: open it anywhere
```

Read more in [public URLs](https://docs.fibre.dev/connect/public-urls.md).

## Snapshots

Take a snapshot of a prepared sandbox, its whole state with memory, so new ones start ready:

```python title="Python" norun reason="the snapshots page runs the same calls" theme={null}
snapshot = prepared.snapshot(name="my-stack")  # new sandboxes start running, where it was
copy = Sandbox.create(snapshot="my-stack")

for s in Snapshot.list():
    print(s.name, s.size_bytes, s.monthly_cost_usd)
Snapshot.get("my-stack").delete()
```

Read more in [snapshots](https://docs.fibre.dev/setup/snapshots.md), including [what they cost](https://docs.fibre.dev/setup/snapshots.md#what-it-costs).

## Browser and desktop

Get links to a sandbox's browser, or to its desktop:

```python title="Python" norun reason="the browser and desktop pages run the same calls" theme={null}
links = sbx.browser()  # connect Playwright to links.cdp_url
sbx.close_browser()

desk = Sandbox.create(needs=["desktop"])
link = desk.desktop()  # link.url: a single-use link to watch and use it
```

Read more in [browser](https://docs.fibre.dev/connect/browser.md) and [desktop](https://docs.fibre.dev/connect/desktop.md).

## Secrets

Store a secret once, then give it to the one command that needs it, by name. Inside the sandbox it is an
environment variable; its value is never returned by the API:

```python title="Python" norun reason="the secrets page runs the same calls" theme={null}
import os

Secret.set("OPENAI_API_KEY", os.environ["OPENAI_API_KEY"])
sbx.run("python3 agent.py", secrets=["OPENAI_API_KEY"])  # this command only
agent = Sandbox.create(secrets=["OPENAI_API_KEY"])  # every command in it
```

Read more in [secrets](https://docs.fibre.dev/production/secrets.md).

## asyncio

`AsyncSandbox` has the same methods as `Sandbox`, for code that uses `asyncio`: you `await` the calls, read output
with `async for`, and use `async with` to delete a sandbox at the end. It is the natural way to run many sandboxes
at the same time:

```python title="Python" run theme={null}
import asyncio

from fibre import AsyncSandbox


async def square(n: int) -> str:
    async with await AsyncSandbox.create(lifetime=300, labels={"docs": "sdk"}) as one:
        r = await one.run(["python3", "-c", f"print({n} ** 2)"])
        return r.stdout.strip()


async def main() -> None:
    print(await asyncio.gather(*(square(n) for n in range(1, 4))))  # ['1', '4', '9']


asyncio.run(main())
```

The async classes are `AsyncSandbox`, `AsyncCommand`, `AsyncFiles`, `AsyncSnapshot`, `AsyncSecret` and `AsyncFibre`.

## Errors

When a call fails, the SDK raises a `FibreError` with `status`, `code`, `request_id` and `docs_url`. Each kind of
error has its own class, so you can catch exactly the ones you expect:

```python title="Python" run theme={null}
sbx.delete()
try:
    Sandbox.get(sbx.id)
except NotFoundError as e:
    print(e.status, e.code)  # 404 sandbox_not_found
```

| Class | When |
| - | - |
| `ValidationError` | 400, 422: the request is wrong |
| `AuthenticationError` | 401: no key, or a bad one |
| `PaymentRequiredError` | 402: billing |
| `PermissionDeniedError` | 403: the key may not do this |
| `NotFoundError` | 404 |
| `ConflictError` | 409: the state does not allow it |
| `RateLimitError` | 429, with `retry_after` |
| `ServerError` | 5xx |
| `FibreConnectionError`, `FibreTimeoutError` | No answer, or a command past its `timeout` |

The last two have `Fibre` in their names so that they do not hide Python's own `ConnectionError` and
`TimeoutError`. Read more in [errors, retries and limits](https://docs.fibre.dev/production/errors-and-limits.md).

## Any API call

If the SDK does not have a method for a call yet, use the client's `json()` method. It still sends your key,
retries temporary failures and raises typed errors:

```python title="Python" run theme={null}
fibre = Fibre()
pricing = fibre.json("GET", "/v1/pricing")
print(pricing["sizes"]["medium"]["per_hour"])  # 0.03
```

Pass the body as `json=`, the query as `params=` and raw bytes as `content=`. `fibre.request()` gives you the raw
response, and `fibre.stream()` one you read as it arrives.

## Methods

For reference, here is every class and method in the SDK:

| `Sandbox` | Does |
| - | - |
| `Sandbox.create(**options)` | Start a sandbox; returns when it runs |
| `Sandbox.get(id)` | One sandbox by ID |
| `Sandbox.list(labels=…)` | Iterate over sandboxes, newest first, paging for you |
| `sbx.run(cmd, cwd=…, env=…, secrets=…, timeout=…)` | Run and wait; returns `exit_code`, `stdout`, `stderr` |
| `sbx.spawn(cmd, cwd=…, env=…, secrets=…, keep=…, stdin=…, timeout_sec=…)` | Start in the background; returns a `Command` |
| `sbx.command(id)`, `sbx.commands()` | Find commands again |
| `sbx.files` | `write`, `read`, `read_bytes`, `list`, `stat`, `remove` |
| `sbx.update(lifetime=…, idle_timeout=…, labels=…)` | Change what can change; `lifetime=None` removes the lifetime |
| `sbx.refresh()` | Re-read its status |
| `sbx.snapshot(name=…)` | Take a snapshot: its whole state, with memory |
| `sbx.browser(ttl=…)`, `sbx.close_browser()` | Links to its browser; close it |
| `sbx.desktop()` | A link to its desktop |
| `sbx.delete()`, `with Sandbox.create() as sbx:` | Delete it |
| Properties | `id`, `status`, `runtime`, `runtime_reason`, `url`, `hostname`, `labels`, `secrets`, `expires_at`, `idle_timeout`, `data` |

| `Command` | Does |
| - | - |
| `output(follow=…)` | Its output as it is written (an iterator of chunks with `stream`, `data` and `raw`) |
| `wait(timeout=…)` | Wait for the end; returns `exit_code`, `status`, `stdout`, `stderr` |
| `write(data)`, `close_stdin()` | Feed its standard input |
| `kill(signal=…, grace=…)` | Stop it: `TERM`, then `KILL` after `grace` seconds |
| `refresh()` | Re-read its status |
| Properties | `id`, `status`, `exit_code`, `pid`, `log` |

| `Snapshot` | Does |
| - | - |
| `Snapshot.get(name)`, `Snapshot.list()` | Find snapshots |
| `snapshot.delete()` | Delete one (after the sandboxes started from it) |
| Properties | `name`, `source` (the sandbox it was taken of), `size_bytes`, `monthly_cost_usd`, `created_at` |

| `Secret` | Does |
| - | - |
| `Secret.set(name, value)` | Store a secret, or replace its value |
| `Secret.get(name)`, `Secret.list()` | Find secrets (never their values) |
| `secret.delete()` | Delete one |
| Properties | `name`, `version`, `created_at`, `updated_at` |

| `Fibre` | Does |
| - | - |
| `Fibre(api_key=…, base_url=…, timeout=…, max_retries=…)` | A configured client |
| `fibre.json(method, path, json=…, params=…, headers=…)` | Any API call, JSON in and out |


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