Every command in your CLI builds its own HTTP client, repeats the auth header, and maps errors its
own way, so items list reports a 401 as a traceback while items get prints a message. Moving
the calls onto the generated SDK fixes that. A CLI that imports the SDK at the top then loads all
of it before it parses a flag, so every --help waits for it.
What you get
You will end up with a Typer CLI whose commands share one SDK client, whose flags match the SDK’s
parameters under test, and whose --help loads no SDK module. This is for you if a generated
Python SDK already exists for the API your CLI calls.
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. 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 | 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 | 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 | 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 | 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 | 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 | 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, and
generates. The package it wrote is committed under generated/py.
(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,
and the root callback puts a Session
on ctx.obj for every command.
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.
@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
python3 cli.py --help
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.
@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.
python3 run.py items list --limit 3
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, 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.
python3 importcheck.py
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.
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 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 says the Python package is in initial
development, and Hey API’s TypeScript generator, a separate package, was not run here.
python3 run.py --sdk hey-api items list --limit 3
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 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 describes. Set it high enough to
mirror the parameters as flags. Its Python
page says operation
groups load on first access. If a Go binary suits your users, speakeasy quickstart --target cli
generates a Cobra 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.
python3 test_cli.py
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.
python3 pitfall.py
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.
cat generated/PAGE-PARAM
@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
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.
Footnotes
-
Speakeasy’s CLI page 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 aninternal/sdkdirectory with the generated Go SDK inside it, so the CLI and the SDK it calls ship as one Go module. ↩︎ Back to text -
The 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. ↩︎ Back to text -
httpx’s
normalize_pathdrops.and..segments from the path of any URL with a scheme or a host, and cites RFC 3986 section 5.2.4 in a comment. That section’sremove_dot_segmentsis 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. ↩︎ Back to text