> Complete content index: https://narsil.sondelali.com/llms.txt

# Python client

> Reach a Narsil server from Python through a blocking client or an async one, write and search documents, follow a rebalance, and keep working while one of several servers is down.

URL: https://narsil.sondelali.com/docs/python-client
Section: Clients
Version: 0.4 (@delali/narsil@0.4.3, latest)

`narsil-client` sends your calls to a Narsil server over HTTP from Python 3.11 or later. It has one typed method for every route in the server's OpenAPI file, with the operation name of the route in snake case, so `createIndex` becomes `create_index`. `NarsilClient` blocks on each call, while `AsyncNarsilClient` offers the same methods as coroutines that you can await under asyncio or trio. To search an index inside the Python process with no server at all, install the `delali-narsil` package and start from [Getting started](/docs/getting-started).

On this page, you'll build `search_client.py`, a program that searches a server, writes documents to it, follows a rebalance that the server continues after the call returns, and keeps working while one of two servers is down. Each code block below holds the whole file, with green lines marking the lines that you add at each step and struck lines marking the lines that you remove.

## Install the client

The examples on this page use version 0.2.0.

```bash
pip install narsil-client==0.2.0
```

The package depends on `httpx`, `pydantic`, `anyio`, and `typing-extensions`, but not on NumPy. When a document holds a NumPy array, the client sends the list of numbers that the array holds.

From version 0.2.0, `get_changes` and `update_changes` return and set the change capture setting of an index, while `follow_changes` opens the change feed of an index on either client. The feed requires the `changes` extra, which adds `websockets` and `msgpack` to the install. When you install the client without that extra, `follow_changes` raises `CONFIG_INVALID`. The feed and its install command are on [Change capture](/docs/change-capture).

## Start a server to call

The client calls a server from the TypeScript package, so start one in a second terminal. The server below listens on port 7700 and accepts only the requests that hold the API key, as in the examples on [HTTP server](/docs/http-server). Install the package and uWebSockets.js, the web server that the package uses, into a Node.js 24 project whose `package.json` sets `"type": "module"`.

```bash pm
pnpm add -E @delali/narsil uWebSockets.js@github:uNetworking/uWebSockets.js#v20.70.0
```

```ts title="server.ts"
import { createNarsil } from '@delali/narsil'
import { createServer } from '@delali/narsil/server'

const API_KEY = process.env.NARSIL_API_KEY ?? 'support-desk-key'

const engine = await createNarsil({ workers: { enabled: false } })
const server = createServer(engine, {
  host: '127.0.0.1',
  port: 7700,
  onRequest: (request) =>
    request.headers.authorization === `Bearer ${API_KEY}`
      ? undefined
      : { status: 401, code: 'UNAUTHORISED', message: 'Send the API key as a bearer token.' },
})

await server.listen()
console.log('Narsil is listening on http://127.0.0.1:7700')

process.once('SIGINT', async () => {
  await server.shutdown()
})
```

Node.js 24 can execute a TypeScript file as it stands, so start the server with `node server.ts` and keep it going while you work through this page.

```txt result open
Narsil is listening on http://127.0.0.1:7700
```

Press Ctrl+C in that terminal when you finish, which makes the `SIGINT` handler shut the server down along with its engine.

## Connect and search

`NarsilClient` takes the server's address, along with an `api_key` that the client sends as a bearer token on every request. Every method that takes a body accepts a plain dictionary in the server's JSON field names, such as `termMatch`, or the Pydantic model from `narsil_client.models` that the client generates for that body. The client returns every answer as one of those models, with its fields in snake case, while a stored document stays a plain dictionary. The program drops the index at the end, so that you can execute it again against the same server.

```python title="search_client.py"
import json
import os

from narsil_client import NarsilClient

API_KEY = os.environ.get("NARSIL_API_KEY", "support-desk-key")

with NarsilClient("http://127.0.0.1:7700", api_key=API_KEY) as client:
    client.create_index({"name": "articles", "config": {"schema": {"title": "string", "body": "string"}}})
    client.insert_batch(
        "articles",
        [
            {"id": "refund-timing", "title": "How a refund reaches your bank", "body": "A refund returns to the card that paid for the order."},
            {"id": "parcel-tracking", "title": "Track a parcel after dispatch", "body": "Every dispatched order has a tracking code."},
            {"id": "refund-currency", "title": "Refunds in another currency", "body": "Your bank converts a refund at the rate on the day it arrives."},
        ],
    )
    client.wait_for_writes("articles")

    found = client.query("articles", {"term": "refund", "document": {"include": ["title"]}})

    print(json.dumps([{"id": hit.id, "title": hit.document["title"]} for hit in found.hits], indent=2))

    client.drop_index("articles")
```

```json result open
[
  {
    "id": "refund-timing",
    "title": "How a refund reaches your bank"
  },
  {
    "id": "refund-currency",
    "title": "Refunds in another currency"
  }
]
```

The server answers with the same two hits that the [TypeScript client](/docs/client-sdk) receives for this search. The client holds a pool of connections, so keep one client for the lifetime of the application and close it with a `with` block or with `close_connections()`. You can share one `NarsilClient` between threads safely.

## Write a document under an id that you choose

`put` writes a document at the id that you give it and returns `created`, which is true when the call creates the document and false when it replaces one. `get` returns `None` for an id that the index lacks, while it raises for every other failure.

```python title="search_client.py"
import json
import os

from narsil_client import NarsilClient

API_KEY = os.environ.get("NARSIL_API_KEY", "support-desk-key")

with NarsilClient("http://127.0.0.1:7700", api_key=API_KEY) as client:
    client.create_index({"name": "articles", "config": {"schema": {"title": "string", "body": "string"}}})
    client.insert_batch(
        "articles",
        [
            {"id": "refund-timing", "title": "How a refund reaches your bank", "body": "A refund returns to the card that paid for the order."},
            {"id": "parcel-tracking", "title": "Track a parcel after dispatch", "body": "Every dispatched order has a tracking code."},
            {"id": "refund-currency", "title": "Refunds in another currency", "body": "Your bank converts a refund at the rate on the day it arrives."},
        ],
    )
    client.wait_for_writes("articles")

    found = client.query("articles", {"term": "refund", "document": {"include": ["title"]}})  # [!code --]
    created = client.put(  # [!code ++:11]
        "articles",
        "password-reset",
        {"document": {"title": "Reset your password", "body": "Request a reset link from the sign-in page."}},
    )
    replaced = client.put(
        "articles",
        "password-reset",
        {"document": {"title": "Reset your password", "body": "Request a reset link from the sign-in page, and it expires after one hour."}},
    )
    missing = client.get("articles", "gift-cards")

    print(json.dumps([{"id": hit.id, "title": hit.document["title"]} for hit in found.hits], indent=2))  # [!code --]
    print(json.dumps({"created": created.model_dump(), "replaced": replaced.model_dump(), "missing": missing}, indent=2))  # [!code ++]

    client.drop_index("articles")
```

```json result open
{
  "created": {
    "id": "password-reset",
    "created": true
  },
  "replaced": {
    "id": "password-reset",
    "created": false
  },
  "missing": null
}
```

The first `put` creates the article, while the second replaces it, so `created` holds `true` and then `false`.

## Follow the work that outlasts a request

A rebalance, a restore, an analysis rebuild, a vector optimisation, and a started import can take longer than a request should wait. For each of them, the server answers at once with a task record and continues the work. `wait_for_task` then polls that task every 250 ms until the work finishes.

```python title="search_client.py"
import json
import os

from narsil_client import NarsilClient

API_KEY = os.environ.get("NARSIL_API_KEY", "support-desk-key")

with NarsilClient("http://127.0.0.1:7700", api_key=API_KEY) as client:
    client.create_index({"name": "articles", "config": {"schema": {"title": "string", "body": "string"}}})
    client.insert_batch(
        "articles",
        [
            {"id": "refund-timing", "title": "How a refund reaches your bank", "body": "A refund returns to the card that paid for the order."},
            {"id": "parcel-tracking", "title": "Track a parcel after dispatch", "body": "Every dispatched order has a tracking code."},
            {"id": "refund-currency", "title": "Refunds in another currency", "body": "Your bank converts a refund at the rate on the day it arrives."},
        ],
    )
    client.wait_for_writes("articles")

    created = client.put(
        "articles",
        "password-reset",
        {"document": {"title": "Reset your password", "body": "Request a reset link from the sign-in page."}},
    )
    replaced = client.put(
        "articles",
        "password-reset",
        {"document": {"title": "Reset your password", "body": "Request a reset link from the sign-in page, and it expires after one hour."}},
    )
    missing = client.get("articles", "gift-cards")

    print(json.dumps({"created": created.model_dump(), "replaced": replaced.model_dump(), "missing": missing}, indent=2))  # [!code --]
    client.update_partition_config("articles", {"maxPartitions": 2})  # [!code ++:15]
    started = client.rebalance("articles", {"targetPartitionCount": 2})
    finished = client.wait_for_task(started.id, wait_timeout_ms=60_000)
    stats = client.get_stats("articles")

    print(
        json.dumps(
            {
                "started": {"type": started.type, "status": started.status},
                "finished": finished.status,
                "partitionCount": stats.partition_count,
            },
            indent=2,
        )
    )

    client.drop_index("articles")
```

```json result open
{
  "started": {
    "type": "rebalance",
    "status": "running"
  },
  "finished": "succeeded",
  "partitionCount": 2
}
```

The server answers the rebalance with a record whose status is `running`. `wait_for_task` then returns once the status reaches `succeeded`, by which point the index holds two partitions. A task can also end as `failed`, with the error in the record's `error` field, or as `cancelled` after `cancel_task`. `wait_for_task` returns for a failed task without raising, because the record of a part-finished import holds the count of the documents that the server indexes before the failure, so check the status of the record that it returns. With `wait_timeout_ms`, `wait_for_task` raises `CLIENT_TASK_TIMEOUT` once that time passes, while the server continues the task. With `on_progress`, you pass a function that the client calls each time the record changes, such as one that updates a progress bar for `start_import`.

## Keep working while one server is down

The address can also be a list, such as one for each node of a cluster or each copy of a server behind your load balancer. The client sends each request to the next address in the list after the address of the previous request, so that the requests spread across the list. When a server refuses the connection, the client retries the request on the next address and skips the refused address for 1 second, doubling that wait after each further refusal, up to 30 seconds. `url_skip_ms` and `max_url_skip_ms` set those two intervals. In the block below, port 7701 stands in for a stopped server, since no process listens on it.

```python title="search_client.py"
import json
import os

from narsil_client import NarsilClient

API_KEY = os.environ.get("NARSIL_API_KEY", "support-desk-key")

with NarsilClient("http://127.0.0.1:7700", api_key=API_KEY) as client:
    client.create_index({"name": "articles", "config": {"schema": {"title": "string", "body": "string"}}})
    client.insert_batch(
        "articles",
        [
            {"id": "refund-timing", "title": "How a refund reaches your bank", "body": "A refund returns to the card that paid for the order."},
            {"id": "parcel-tracking", "title": "Track a parcel after dispatch", "body": "Every dispatched order has a tracking code."},
            {"id": "refund-currency", "title": "Refunds in another currency", "body": "Your bank converts a refund at the rate on the day it arrives."},
        ],
    )
    client.wait_for_writes("articles")

    created = client.put(
        "articles",
        "password-reset",
        {"document": {"title": "Reset your password", "body": "Request a reset link from the sign-in page."}},
    )
    replaced = client.put(
        "articles",
        "password-reset",
        {"document": {"title": "Reset your password", "body": "Request a reset link from the sign-in page, and it expires after one hour."}},
    )
    missing = client.get("articles", "gift-cards")

    client.update_partition_config("articles", {"maxPartitions": 2})
    started = client.rebalance("articles", {"targetPartitionCount": 2})
    finished = client.wait_for_task(started.id, wait_timeout_ms=60_000)
    stats = client.get_stats("articles")

    print(  # [!code --:10]
        json.dumps(
            {
                "started": {"type": started.type, "status": started.status},
                "finished": finished.status,
                "partitionCount": stats.partition_count,
            },
            indent=2,
        )
    )
    with NarsilClient(["http://127.0.0.1:7701", "http://127.0.0.1:7700"], api_key=API_KEY) as nodes:  # [!code ++:9]
        written = nodes.put(
            "articles",
            "gift-cards",
            {"document": {"title": "Pay with a gift card", "body": "Enter the gift card code at checkout."}},
        )
        reads = [nodes.query("articles", {"term": "gift"}).count for _ in range(3)]

    print(json.dumps({"written": written.model_dump(), "reads": reads}, indent=2))

    client.drop_index("articles")
```

```json result open
{
  "written": {
    "id": "gift-cards",
    "created": true
  },
  "reads": [
    1,
    1,
    1
  ]
}
```

The write and all three searches succeed, because the client retries each request that fails on port 7701 on port 7700. The client counts a `GET`, a search, a preflight, a suggestion, a document list, and a multi-get as reads. It retries a read on the next address after a refused or broken connection, a timeout, or an answer of 502, 503, or 504. Once every address fails that way, the client sends the read once more, so a list of N addresses can take N + 1 requests. The client retries a write only when the connection fails before the client sends any byte of the request, as with a refused connection or a name that does not resolve, or when the server answers `NODE_NOT_READY`. A server can apply a write that reaches it, so after a timeout or a broken connection, the client raises the error to you and sends nothing more. The client sends a body that you pass as a file or an iterator to one address only, because it can't read that body twice.

## Handle failures

The client raises every failure as a `NarsilError`, with the code from the server in `code` and the HTTP status in `status`. The program below asks for an index that the server lacks, and then it sends a search without the API key, which the server's `onRequest` hook refuses.

```python title="search_client.py"
import json
import os

from narsil_client import NarsilClient  # [!code --]
from narsil_client import NarsilClient, NarsilError  # [!code ++]

API_KEY = os.environ.get("NARSIL_API_KEY", "support-desk-key")

with NarsilClient("http://127.0.0.1:7700", api_key=API_KEY) as client:
    client.create_index({"name": "articles", "config": {"schema": {"title": "string", "body": "string"}}})
    client.insert_batch(
        "articles",
        [
            {"id": "refund-timing", "title": "How a refund reaches your bank", "body": "A refund returns to the card that paid for the order."},
            {"id": "parcel-tracking", "title": "Track a parcel after dispatch", "body": "Every dispatched order has a tracking code."},
            {"id": "refund-currency", "title": "Refunds in another currency", "body": "Your bank converts a refund at the rate on the day it arrives."},
        ],
    )
    client.wait_for_writes("articles")

    created = client.put(
        "articles",
        "password-reset",
        {"document": {"title": "Reset your password", "body": "Request a reset link from the sign-in page."}},
    )
    replaced = client.put(
        "articles",
        "password-reset",
        {"document": {"title": "Reset your password", "body": "Request a reset link from the sign-in page, and it expires after one hour."}},
    )
    missing = client.get("articles", "gift-cards")

    client.update_partition_config("articles", {"maxPartitions": 2})
    started = client.rebalance("articles", {"targetPartitionCount": 2})
    finished = client.wait_for_task(started.id, wait_timeout_ms=60_000)
    stats = client.get_stats("articles")

    with NarsilClient(["http://127.0.0.1:7701", "http://127.0.0.1:7700"], api_key=API_KEY) as nodes:
        written = nodes.put(
            "articles",
            "gift-cards",
            {"document": {"title": "Pay with a gift card", "body": "Enter the gift card code at checkout."}},
        )
        reads = [nodes.query("articles", {"term": "gift"}).count for _ in range(3)]

    print(json.dumps({"written": written.model_dump(), "reads": reads}, indent=2))  # [!code --]
    failures = []  # [!code ++:12]
    try:
        client.query("faqs", {"term": "refund"})
    except NarsilError as error:
        failures.append({"code": error.code, "status": error.status})
    with NarsilClient("http://127.0.0.1:7700") as anonymous:
        try:
            anonymous.query("articles", {"term": "refund"})
        except NarsilError as error:
            failures.append({"code": error.code, "status": error.status})

    print(json.dumps(failures, indent=2))

    client.drop_index("articles")
```

```json result open
[
  {
    "code": "INDEX_NOT_FOUND",
    "status": 404
  },
  {
    "code": "UNAUTHORISED",
    "status": 401
  }
]
```

The client passes the hook's code to your program unchanged, so a branch that you write against `UNAUTHORISED` works whichever node answers. `details` holds the values that the server sends with the error. The client itself raises four codes, which `ClientErrorCodes` holds:

| Code | The client raises it when |
| --- | --- |
| `CLIENT_CONNECTION_FAILED` | The client can't reach any server, or the connection breaks before the answer arrives. |
| `CLIENT_REQUEST_TIMEOUT` | The deadline passes before the answer arrives. |
| `CLIENT_INVALID_RESPONSE` | The answer holds neither a Narsil error nor the shape that the OpenAPI file gives for the route, as with the HTML error page of a proxy, or it exceeds `max_response_bytes`. |
| `CLIENT_TASK_TIMEOUT` | `wait_for_task` reaches `wait_timeout_ms` while the task is still in progress. |

The client gives every try of a request 30 seconds, after which the request fails with `CLIENT_REQUEST_TIMEOUT`. Set `timeout_ms` on the client to change that for every request, or pass `timeout_ms` to one call. A value of 0 makes the client wait for as long as the server takes. The methods that move a corpus or a whole index wait without a deadline unless you set `timeout_ms` on the client or on the call. Those methods are `import_documents`, `start_import`, `import_ndjson`, `snapshot`, `restore`, `export_documents`, `import_document_export`, and `sync_snapshot`. You can set `headers` and `max_response_bytes` in the same two places, on the client for every request or on one call. The client raises `CONFIG_INVALID` before it sends anything when a setting is out of range, such as an empty list of addresses or an address whose scheme is neither `http` nor `https`.

## Call the server from async code

`AsyncNarsilClient` takes the same settings, and each of its methods is a coroutine. The program below loads the same articles and sends three searches at once from an `anyio` task group, each with a deadline of two seconds.

```python title="async_search.py"
import json
import os

import anyio
from narsil_client import AsyncNarsilClient

API_KEY = os.environ.get("NARSIL_API_KEY", "support-desk-key")


async def main() -> None:
    async with AsyncNarsilClient("http://127.0.0.1:7700", api_key=API_KEY) as client:
        await client.create_index({"name": "articles", "config": {"schema": {"title": "string", "body": "string"}}})
        await client.insert_batch(
            "articles",
            [
                {"id": "refund-timing", "title": "How a refund reaches your bank", "body": "A refund returns to the card that paid for the order."},
                {"id": "parcel-tracking", "title": "Track a parcel after dispatch", "body": "Every dispatched order has a tracking code."},
                {"id": "refund-currency", "title": "Refunds in another currency", "body": "Your bank converts a refund at the rate on the day it arrives."},
            ],
        )
        await client.wait_for_writes("articles")

        terms = ["refund", "parcel", "bank"]
        counts: dict[str, int] = {}

        async def count(term: str) -> None:
            found = await client.query("articles", {"term": term}, timeout_ms=2_000)
            counts[term] = found.count

        async with anyio.create_task_group() as group:
            for term in terms:
                group.start_soon(count, term)

        print(json.dumps({term: counts[term] for term in terms}, indent=2))

        await client.drop_index("articles")


anyio.run(main)
```

```json result open
{
  "refund": 2,
  "parcel": 1,
  "bank": 2
}
```

The program sends the three searches from the task group without waiting for one answer before the next request, while the three requests share the client's pool of connections. To stop a call, cancel the task or the scope that awaits it. The async client follows the same rules as the blocking one for retrying on another address and for raising errors. To add a proxy or custom certificates, build an `httpx.AsyncClient` and pass it as `http_client`, or pass an `httpx.Client` to `NarsilClient` in the same way. The Narsil client leaves that HTTP client open when it closes.

## Where to go next

- Read [TypeScript client](/docs/client-sdk) and [Go client](/docs/go-client) for the same routes from those languages.
- Read [HTTP server](/docs/http-server) for what each route does and for the hook that checks the key.
- Read [Device sync](/docs/device-sync) for `update_sync`, which turns sync on for one user's index from Python.
- Read [Errors](/docs/errors) for the codes that a server sends.
