# How to build a Typer CLI that reuses a generated Python SDK

> Give each API resource a Typer sub-app, build the generated client once from the root callback, mirror its parameters as flags, and keep its import out of --help.

Source: https://voxgig.com/howto/typer-cli-over-a-generated-python-sdk

- Audience: api-consumer
- Level: intermediate
- Languages: python
- Verified: 2026-11-21
- Published: 2026-11-21

## Short answer

Build the Typer app with one sub-app per resource through app.add_typer. In the root callback, put a session object on ctx.obj that imports and constructs the generated SDK client on first use, once. Mirror each SDK parameter as an Annotated option with the same name, type, and help, and test that the two agree. Then check with python -X importtime that --help loads no SDK module.

---
## You will need

Python 3.12 or later, a generated Python SDK for the API, and Typer. Verified 2026-11-21 against
Python 3.13.18, Typer 0.29.2, @voxgig/sdkgen 4.44.3, `@hey-api/openapi-python` 0.0.24,
`openapi-python-client` 0.30.0, and httpx 0.28.1. The document, `api.json`, describes a Stockroom
API with three operations, a bearer token, and cursor paging. The command tree follows
[Derive a noun-verb command tree from an OpenAPI document](/howto/derive-a-command-tree-from-operation-ids). Every
command runs against `server.py`, a local stand-in that refuses a parameter the document does not
declare.

## Approaches compared

| Approach | When it fits | What it costs you | When to pick something else |
| --- | --- | --- | --- |
| [Click](https://click.palletsprojects.com/en/stable/options/) | The team writes Click already, or needs Click plug-ins, which Typer's own copy of Click does not support | Each flag is declared in a decorator and again as a parameter, two places to keep in step | You want types and help read from the function signature |
| [Hey API Python client](https://heyapi.dev/docs/openapi/python/get-started) | You want Pydantic models for responses and for the query parameters | In 0.0.24 its methods take no parameters, so paths, queries, and auth are yours | The commands should call methods that carry their parameters |
| [httpx called directly](https://www.python-httpx.org/advanced/clients/) | Two or three endpoints, and no SDK to wait for | The auth header, error mapping, and path escaping written in the CLI, with no types | The API has more than a handful of operations |
| [`openapi-python-client`](https://github.com/openapi-generators/openapi-python-client) | You want keyword signatures and `attrs` models that a command can mirror | A documented 4xx with no body parses to `None`, so every command checks the result's type | The API owner already publishes an SDK |
| [sdkgen Python target](https://github.com/voxgig/sdkgen) | The API owner generates with sdkgen, and the CLI should share its features | Untyped dict arguments, a `TypedDict` per call kept beside them, and a `page=1` to remove | You need keyword signatures to mirror into flags |
| [Speakeasy Python SDK](https://www.speakeasy.com/docs/sdks/languages/python/methodology-python) | The vendor ships a Speakeasy SDK, or a generated CLI would serve instead | Generating one needs a Speakeasy account, and its generated CLI is Go, not Python | The OpenAPI document cannot leave your machine |

Voxgig maintains sdkgen. It sits in the table under the same four columns as the other five, as one
option rather than the recommendation.

The generated clients give the commands one auth path and one error type, and they tie a CLI
release to an SDK release. httpx in the commands is the lightest option and leaves you to rewrite
what the SDK already handles, which on this API includes the escaping of an item id.

## Give each resource a sub-app and build the client once

`generate.sh` scaffolds the sdkgen project with the `py` target and the
[`paging` feature](https://github.com/voxgig/sdkgen/blob/main/docs/reference/features.md), and
generates. The package it wrote is committed under `generated/py`.

```bash title="generate.sh"
(cd "$WORK" && npx --yes @voxgig/create-sdkgen@0.31.9 stockroom --def api.json --target py \
  --feature paging > scaffold.txt 2>&1)
(cd "$WORK/stockroom-sdk/.sdk" && npm run generate > ../../generate.txt 2>&1)
```

The CLI has one [sub-app per resource](https://typer.tiangolo.com/tutorial/subcommands/add-typer/),
and the [root callback](https://typer.tiangolo.com/tutorial/commands/callback/) puts a `Session`
on `ctx.obj` for every command.

```py title="cli.py"
app = typer.Typer(help="Read stock levels from the Stockroom API.", no_args_is_help=True,
                  add_completion=False, pretty_exceptions_enable=False, rich_markup_mode=None)
items_app = typer.Typer(help="Items in stock.", no_args_is_help=True)
suppliers_app = typer.Typer(help="Suppliers.", no_args_is_help=True)
app.add_typer(items_app, name="items")
app.add_typer(suppliers_app, name="suppliers")


@app.callback()
def root(
    ctx: typer.Context,
    base_url: Annotated[str, typer.Option(help="The API's base URL, /v1 included.")] = "https://api.example.com/v1",
    token: Annotated[str, typer.Option(envvar="STOCKROOM_TOKEN", show_default=False, help="Bearer token.")] = "",
    sdk: Annotated[Sdk, typer.Option(help="The client the commands call through.")] = Sdk.sdkgen,
) -> None:
    ctx.obj = Session(base_url, token, sdk)
```

The root callback runs before `items list --help` prints, so it must not build the client. The
session builds it on first use, and that is where the SDK is imported.

```py title="session.py"
    @property
    def api(self):
        if self._api is None:
            import backends  # the SDK is imported here, not when the CLI starts

            if not self.token:
                raise backends.ApiError(None, "no token: set STOCKROOM_TOKEN or pass --token")

            self._api = backends.make(self.sdk.value, self.base_url, self.token)
            self.builds += 1
        return self._api
```

```bash
python3 cli.py --help
```

```text output
Usage: stockroom [OPTIONS] COMMAND [ARGS]...

  Read stock levels from the Stockroom API.

Options:
  --base-url <str>                The API's base URL, /v1 included.  [default:
                                  https://api.example.com/v1]
  --token <str>                   Bearer token.  [env var: STOCKROOM_TOKEN]
  --sdk <sdkgen|openapi-python-client|hey-api|httpx>
                                  The client the commands call through.
                                  [default: sdkgen]
  --help                          Show this message and exit.

Commands:
  items      Items in stock.
  suppliers  Suppliers.
```

## Mirror the SDK's parameters as flags

Typer reads each flag's name, type, and help from the command's signature. The sdkgen SDK's
`list` takes an unannotated dict, and its `stockroom_types` module defines `ItemListMatch`, a
`TypedDict` of `limit: int` and `cursor: str`. The command declares those two names with those
types, and takes the help and range from the document.

```py title="cli.py"
@items_app.command("list")
def items_list(
    ctx: typer.Context,
    limit: Annotated[Optional[int], typer.Option(min=1, max=100, help="Items per page.")] = None,
    cursor: Annotated[Optional[str], typer.Option(help="The next_cursor of the previous page.")] = None,
    as_json: Annotated[bool, typer.Option("--json", help="Print the page as JSON.")] = False,
) -> None:
    """List items, one page at a time."""
    records, next_cursor = call(lambda: ctx.obj.api.list_items(limit=limit, cursor=cursor))
    emit(records, as_json, [("id", 8), ("name", 18), ("quantity", 5), ("location", 3)],
         {"next_cursor": next_cursor})
    if next_cursor and not as_json:
        typer.echo(f"next: --cursor {next_cursor}")
```

A test compares these options with `ItemListMatch`, with `list_items.sync` from
`openapi-python-client`, and with Hey API's `ListItemsQuery`. A regenerated SDK that renames a
parameter then fails the build. `run.py` starts the
stand-in and runs the CLI with the token in `STOCKROOM_TOKEN`.

```bash
python3 run.py items list --limit 3
```

```text output
itm_001   Hex bolt M6         1200   A1
itm_002   Hex nut M6          940    A1
itm_003   Washer M6           3100   A2
next: --cursor cur_003
requests: GET /v1/items?limit=3
```

The request carries `limit=3` and no `page`. That takes an extension of the sdkgen client,
`NoPageNumber` in `backends.py`, which runs after the paging feature and drops the page number
from a request with no cursor.

## Keep the SDK import out of help

`importcheck.py` runs `--help` under [`python -X
importtime`](https://docs.python.org/3/using/cmdline.html), which prints a line per module
imported, and counts the SDK's modules. `eager_cli.py` imports the SDK at the top, and
`rich_cli.py` turns Typer's Rich help back on.

```bash
python3 importcheck.py
```

```text output
cli.py --help: stockroom_sdk modules 0; rich no
cli.py items list --help: stockroom_sdk modules 0; rich no
rich_cli.py --help: stockroom_sdk modules 0; rich yes
rich_cli.py items list --help: stockroom_sdk modules 0; rich yes
eager_cli.py --help: stockroom_sdk modules 52; rich no
eager_cli.py items list --help: stockroom_sdk modules 52; rich no
```

`record.sh` timed each `--help` on one machine, on one day, and committed the medians with the
machine's name.

```text title="records/importtime.txt"
one machine: Linux x86_64, 4 CPUs, Intel(R) Xeon(R) Processor @ 2.10GHz
python 3.13.18, typer 0.29.2, median of 15 runs each
  cli.py --help          94.3 ms
  rich_cli.py --help    251.2 ms
  eager_cli.py --help   124.3 ms
  stockroom_sdk import   56.8 ms cumulative, from python -X importtime
```

In that run, Typer's Rich help added more start-up time than the SDK did, by either measure of
the SDK. [`rich_markup_mode=None`](https://typer.tiangolo.com/tutorial/commands/help/) turns the
Rich formatting off, and Typer then imports no Rich module.

## Run the same commands over Hey API and Speakeasy SDKs

Hey API's Python generator wrote `Sdk` methods with no parameters: `list_items(self)` sends
`GET /items` alone, and `get_item(self)` sends the literal path `/items/{itemId}`. The
`HeyApi` backend sends the query and the path on the httpx client the `Sdk` holds, and validates
each answer with the generated Pydantic models. Flags mirror `ListItemsQuery`, which the
generator wrote from the document's parameters. The [get started
page](https://heyapi.dev/docs/openapi/python/get-started) says the Python package is in initial
development, and Hey API's TypeScript generator, a separate package, was not run here.

```bash
python3 run.py --sdk hey-api items list --limit 3
```

```text output
itm_001   Hex bolt M6         1200   A1
itm_002   Hex nut M6          940    A1
itm_003   Washer M6           3100   A2
next: --cursor cur_003
requests: GET /v1/items?limit=3
```

Speakeasy was not run, since [its CLI asks for an account
login](https://www.speakeasy.com/docs/speakeasy-reference/cli/getting-started) before it generates.
Its Python SDK takes keyword parameters while an operation has no more than `maxMethodParams` of
them, and one request object past that, as the [methods
page](https://www.speakeasy.com/docs/sdks/customize/methods) describes. Set it high enough to
mirror the parameters as flags. Its [Python
page](https://www.speakeasy.com/docs/sdks/languages/python/methodology-python) says operation
groups load on first access. If a Go binary suits your users, `speakeasy quickstart --target cli`
[generates a Cobra CLI](https://www.speakeasy.com/docs/cli-generation/create-cli) and no Typer code
is needed.[^1]

## Check it worked

`test_cli.py` runs every command through all four backends against the stand-in, follows the
cursor to the last item, and parses the `--json` output back through each SDK's model.

```bash
python3 test_cli.py
```

```text output
test_a_proxy_in_the_environment_does_not_reach_the_stand_in (__main__.Failures.test_a_proxy_in_the_environment_does_not_reach_the_stand_in) ... ok
test_a_refused_token_exits_1_with_a_message (__main__.Failures.test_a_refused_token_exits_1_with_a_message) ... ok
test_an_empty_or_dot_id_is_refused_before_any_request (__main__.Failures.test_an_empty_or_dot_id_is_refused_before_any_request) ... ok
test_an_id_cannot_reach_another_path (__main__.Failures.test_an_id_cannot_reach_another_path) ... ok
test_no_token_stops_before_any_request (__main__.Failures.test_no_token_stops_before_any_request) ... ok
test_the_paging_feature_alone_sends_an_undeclared_page (__main__.Failures.test_the_paging_feature_alone_sends_an_undeclared_page) ... ok
test_the_stand_in_refuses_what_the_document_does_not_allow (__main__.Failures.test_the_stand_in_refuses_what_the_document_does_not_allow) ... ok
test_click_prints_what_typer_prints (__main__.ListAndGet.test_click_prints_what_typer_prints) ... ok
test_every_backend_prints_the_same_page (__main__.ListAndGet.test_every_backend_prints_the_same_page) ... ok
test_following_the_cursor_reaches_every_item (__main__.ListAndGet.test_following_the_cursor_reaches_every_item) ... ok
test_get_and_suppliers (__main__.ListAndGet.test_get_and_suppliers) ... ok
test_the_json_round_trips_through_each_sdk_model (__main__.ListAndGet.test_the_json_round_trips_through_each_sdk_model) ... ok
test_the_page_param_record_covers_both_releases (__main__.Records.test_the_page_param_record_covers_both_releases) ... ok
test_the_timing_record_shows_what_the_page_says (__main__.Records.test_the_timing_record_shows_what_the_page_says) ... ok
test_typer_runs_its_own_copy_of_click (__main__.Records.test_typer_runs_its_own_copy_of_click) ... ok
test_help_and_range_come_from_the_document (__main__.Shape.test_help_and_range_come_from_the_document) ... ok
test_help_never_imports_the_sdk (__main__.Shape.test_help_never_imports_the_sdk) ... ok
test_the_flags_mirror_each_sdk_signature (__main__.Shape.test_the_flags_mirror_each_sdk_signature) ... ok
test_the_session_builds_one_client_on_first_use (__main__.Shape.test_the_session_builds_one_client_on_first_use) ... ok

----------------------------------------------------------------------
Ran 19 tests

OK
```

The round trip is the check that the CLI prints what the SDK models hold: `Item.from_dict`
from `openapi-python-client` and `Item.model_validate` from Hey API each rebuild every printed
record unchanged. The Click test runs `click_cli.py` through Click's own test runner, because
Typer ships its own copy of Click.[^2]

## When it goes wrong

The first `items list` fails with a 400. sdkgen's paging feature adds `page=1` to every list
request that has no cursor, and this API declares only `limit` and `cursor`. The stand-in refuses
any query parameter the document does not declare, as an API that validates requests against its
document does. An API that ignores unknown parameters answers 200 and never shows the stray
`page=1`. Add an extension that drops it, as `NoPageNumber` does.

```bash
python3 pitfall.py
```

```text output
1. sdkgen's paging feature, without the NoPageNumber extension
   GET /v1/items?limit=3&page=1 -> status 400
2. an item id of ../suppliers
   httpx with an f-string: GET /v1/suppliers -> 200, 3 suppliers
   item_path(): /items/..%2Fsuppliers
   item_path(): not an item id: '..'
3. openapi-python-client with a token the API refuses
   GET /v1/items?limit=20: sync_detailed() status 401, sync() returned None
```

`generate.sh` ran the same probe on the newest release on npm, and `generated/PAGE-PARAM` holds
the result.

```bash
cat generated/PAGE-PARAM
```

```text output
@voxgig/sdkgen 4.44.3: first request GET /v1/items?limit=3&page=1 -> StockroomError status 400
@voxgig/sdkgen 4.45.0: first request GET /v1/items?limit=3&page=1 -> StockroomError status 400
```

`items get ../suppliers` lists suppliers. An f-string put the id into the path, and httpx removed
the dot segments before sending it.[^3] Escape the id as one segment and refuse `.` and `..`, as
`item_path` does.

A refused token prints a traceback. `sync()` from `openapi-python-client` returns `None` for a
documented 401, even with `raise_on_unexpected_status` set. Call `sync_detailed()` and check the
parsed type, as the `OpenapiPythonClient` backend does.

## When not to do this

Do not put a generated SDK under a CLI whose commands call two endpoints. Each SDK release then
becomes a CLI release, and httpx with an escaped path is less to ship.

Do not choose the sdkgen Python target only to get flags typed from signatures. Its calls take a
dict, so the flags mirror a `TypedDict` by hand, and its paging feature needs the extension shown
here on an API without page numbers. It pays off when the API owner publishes the SDK and the CLI
should share its features.

Start from `openapi-python-client` when you want keyword signatures to copy into flags, and from
Hey API's models for a CLI that validates with Pydantic already. Users who want a single binary
rather than a Python tool are served by a Speakeasy-generated CLI, with no Typer code at all.

## Related how-tos

- [Derive a noun-verb command tree from an OpenAPI document](/howto/derive-a-command-tree-from-operation-ids)

- [Map API parameters to CLI arguments and flags](/howto/map-api-parameters-to-cli-flags-and-arguments)

- [Build a Symfony Console CLI over a generated PHP SDK](/howto/symfony-console-cli-over-a-php-sdk)

- [Choose Restish, a generated CLI, or a hand-written one](/howto/choose-restish-generated-or-hand-written-cli)

- [Keep a CLI in sync with an API spec as it changes](/howto/keep-a-cli-in-sync-with-the-spec)

## Last verified

Verified 2026-11-21 against Node 22.23.5, Python 3.13.18, @voxgig/create-sdkgen 0.31.9,
@voxgig/sdkgen 4.44.3, @voxgig/apidef 8.32.4, `@hey-api/openapi-python` 0.0.24,
`openapi-python-client` 0.30.0, Typer 0.29.2, Click 8.5.1, and httpx 0.28.1. Every output block is
what the command preceding it printed. The three generators ran once, in `generate.sh`, and their
packages are committed under `generated/`. Speakeasy was not run; its method signatures, lazy
loading, and CLI target are described from its documentation.

[^1]: Speakeasy's [CLI page](https://www.speakeasy.com/docs/cli-generation/create-cli) lists what the
generated project holds: Cobra command files, a package that keeps settings in
`~/.config/<cliName>/` and secrets in the OS keychain, and a GoReleaser file. It also holds an `internal/sdk` directory with the
generated Go SDK inside it, so the CLI and the SDK it calls ship as one Go module.

[^2]: The [release notes](https://typer.tiangolo.com/release-notes/) for Typer 0.26.0, dated
2026-05-26, list the change that copied Click into Typer as breaking. They say Typer no longer
depends on Click as a third-party dependency. The copy in 0.29.2, `typer/_click`, opens with a
docstring that calls it code taken and adapted from Click 8.3.1, and carries no version string of
its own. The Click this sample installs beside it is 8.5.1, so a Typer app and a Click app in one
environment parse their flags with two different copies of Click's code.

[^3]: httpx's [`normalize_path`](https://github.com/encode/httpx/blob/master/httpx/_urlparse.py)
drops `.` and `..` segments from the path of any URL with a scheme or a host, and cites [RFC 3986 section
5.2.4](https://www.rfc-editor.org/rfc/rfc3986.html#section-5.2.4) in a comment. That section's
`remove_dot_segments` is part of the procedure for resolving a reference against a base URI, and
it applies to the path whether or not the reference was relative.