fastapi2cli package

Subpackages

Submodules

fastapi2cli.expose module

fastapi2cli.expose.expose_app(app: FastAPI, authentication_resolver: AuthenticationResolverBase = None, authenticated_dependencies: list[Callable] = None, request_executor: RequestExecutor = None, additional_parsers: dict[type, Callable[[str], Any]] = None, server_url: str = None, **kwargs: Any) Typer

Expose FastAPI application routes as a Typer CLI.

This function creates a Typer CLI based on the routes defined in a FastAPI application.

Parameters:
  • app (FastAPI) – The FastAPI application to expose.

  • authentication_resolver (AuthenticationResolverBase, optional) – Authentication resolver for the application, defaults to None. which will raise exception if attempting to access an authenticated route

  • authenticated_dependencies (list[Callable], optional) – List of authenticated dependencies, defaults to None. this allows the app to know what endpoint/route is considered as authenticated.

  • request_executor (RequestExecutor, optional) – Request executor for making HTTP requests, defaults to None.

  • additional_parsers (dict[type, Callable[[str], Any]], optional) – Additional parsers for custom types, defaults to None. This is for types that Typer don’t handle and are present in endpoints/routes you want to expose

  • server_url (str, optional) – The base URL of the server, defaults to None. (if set to none the cli server_url parameter will be mandatory)

  • kwargs (Any, optional) – extra arguments to provide to the generated commands as defaults

Returns:

Typer CLI exposing the FastAPI application routes.

Return type:

typer.Typer

fastapi2cli.fastapi_converter module

class fastapi2cli.fastapi_converter.FastAPIConverter(server_interactor_factory: Callable[[str], ServerInteractor], typer_command_generator: TyperCommandGenerator, server_url: str | None = None, **kwargs: Any)

Bases: object

Converts FastAPI routes to Typer commands.

This class is responsible for converting FastAPI routes into Typer commands, enabling them to be used as command-line interfaces (CLIs). It generates Typer command functions for each route and registers them with a Typer application.

Parameters:
  • server_interactor_factory (Callable[[str], ServerInteractor]) – A factory function for creating server interactors.

  • typer_command_generator (TyperCommandGenerator) – A TyperCommandGenerator instance for generating Typer commands.

  • server_url (str, optional) – The base URL of the server, optional.

expose_app_routes_in_typer_cli(app: FastAPI) Typer

Expose all routes in a FastAPI application as Typer commands.

This method exposes all routes in a FastAPI application as Typer commands in a Typer CLI application.

Parameters:

app (FastAPI) – The FastAPI application.

Returns:

The Typer CLI application.

Return type:

typer.Typer

expose_route_in_typer_cli(route: APIRoute | RouteContext, typer_app: Typer)

Expose a route in a Typer CLI.

This method exposes a specific route in a Typer CLI application. It generates a Typer command function for the route and registers it with the Typer application.

Parameters:
  • route (RouteLike) – The FastAPI route to expose.

  • typer_app (typer.Typer) – The Typer application.

generate_function_for_route(route: APIRoute | RouteContext) Callable[[...], Any]

Generate a function for handling a specific route.

This method generates a function that corresponds to a specific route. The function is responsible for making requests to the server using the provided route.

Parameters:

route (RouteLike) – The FastAPI route.

Returns:

The function for handling the route.

Return type:

RequestCaller

fastapi2cli.parsers module

fastapi2cli.parsers.make_parse_literal(container_args: Sequence[str])

Create a function to validate a value against a list of allowed literals.

This function returns a validation function that checks if a given value is in the provided list of literals. If the value is not in the list, a ValueError is raised.

Parameters:

container_args (Sequence[str]) – The list of allowed literals.

Returns:

The validation function.

Return type:

Callable[[str], str]

fastapi2cli.parsers.parse_bytes(value: str) bytes

Parse a command line string into bytes.

bytes cannot be used as a parser directly: bytes("some text") raises TypeError: string argument without an encoding.

Parameters:

value (str) – The string to encode.

Returns:

The UTF-8 encoding of the value.

Return type:

bytes

fastapi2cli.parsers.parse_url(value: str, valid_schemes: list[str] = None) str

Parse a URL and return it if valid.

This function parses the given URL string and validates its scheme against the list of valid schemes. If the URL scheme is not in the list of valid schemes, a ValueError is raised.

Parameters:
  • value (str) – The URL string to parse.

  • valid_schemes (list[str], optional) – The list of schemes to allow (default is [‘http’, ‘https’]).

Returns:

The parsed URL as a string.

Return type:

str

Raises:

ValueError – If the URL does not have a valid scheme.

fastapi2cli.typer_command_generator module

class fastapi2cli.typer_command_generator.TyperCommandGenerator(additional_parsers: dict[type, Callable[[str], Any]] = None)

Bases: object

Generate Typer commands from annotated functions.

This class is responsible for generating Typer commands from functions with annotated parameters. It inspects the annotations and default values of parameters to construct Typer commands with appropriate options and arguments.

Parameters:

additional_parsers (dict[type, Callable[[str], Any]]) – Additional parsers for custom types.

get_parser_for_complex_type(type_: type)

Get parser for a complex type.

This method retrieves a parser for a complex type, such as lists, dictionaries, or unions.

Parameters:

type (type) – The complex type to get a parser for.

Returns:

The parser function.

Return type:

Callable[[str], Any]

get_parser_for_type(type_: type) Callable[[str], Any] | None

Get parser for a specific type.

This method retrieves a parser for a specific type.

Parameters:

type (type) – The type to get a parser for.

Returns:

The parser function.

Return type:

Callable[[str], Any] | None

get_proxy_for_parameter(value: FieldInfo, is_option: bool = False)

Get Typer option/argument proxy for a parameter.

This method constructs a Typer option/argument proxy for a given parameter.

Parameters:
  • value (FieldInfo) – The field info of the parameter.

  • value – force the generation of an option instead of a parameter even if required.

Returns:

The Typer option/argument proxy.

Return type:

typer.Option | typer.Argument

parsers = {<class 'bytes'>: <function parse_bytes>, <class 'ipaddress.IPv4Address'>: <class 'ipaddress.IPv4Address'>, <class 'ipaddress.IPv6Address'>: <class 'ipaddress.IPv6Address'>, <class 'pydantic.networks.HttpUrl'>: <function parse_url>, <class 'pydantic.networks.IPvAnyAddress'>: <class 'pydantic.networks.IPvAnyAddress'>, <class 'pydantic_core._pydantic_core.Url'>: <function parse_url>}
set_function_annotations_for_route(fun: Callable[[...], Any], parameters: dict[str, FieldInfo], server_url: str | None = None, **extra_params: Any) None

Set Typer annotations for a function.

This method sets Typer annotations for a given function based on provided parameters and server URL.

Parameters:
  • fun (RequestCaller) – The function to set annotations for.

  • parameters (dict[str, FieldInfo]) – Dictionary containing parameter names and their field info.

  • server_url (str, optional) – The server base URL (e.g., https://127.0.0.1:443).

fastapi2cli.typer_command_generator.get_inspect_signature(fun: Callable[[...], Any], annotations: dict[str, type], defaults: dict[str, Any]) Signature

Get an inspected signature for a function.

Constructs an inspected signature for a given function based on provided annotations and default values.

Parameters:
  • fun (RequestCaller) – The function to inspect.

  • annotations (Dict[str, type]) – Dictionary containing parameter names and their corresponding annotations.

  • defaults (Dict[str, Any]) – Dictionary containing parameter names and their default values.

Returns:

The inspected signature for the function.

Return type:

inspect.Signature

fastapi2cli.utils module

fastapi2cli.utils.get_optional_type_value(type_: type) type

Get the non-optional type from an Optional[type] or type | None.

This function extracts the non-optional type from a type hint that represents either an Optional[type] or a Union[type, None]. It is used to handle the conversion of Optional[type] into type for compatibility with certain libraries or frameworks.

Parameters:

type (type) – The type hint from which to extract the non-optional type.

Returns:

The non-optional type.

Return type:

type

Raises:

TypeError – If the provided type hint does not match the expected format.

fastapi2cli.utils.get_route_for_function(fastapi_app: FastAPI, fun: Callable) APIRoute | RouteContext

Get the route in FastAPI for a given function.

Parameters:
  • fastapi_app (FastAPI) – The FastAPI application where the function is registered as a route.

  • fun (Callable) – The function to get the route of.

Returns:

The route of the given function, with its path and metadata resolved as described in iter_api_routes().

Return type:

RouteLike

Raises:

ValueError – If the function is not registered inside the FastAPI app.

fastapi2cli.utils.is_optional(field: type) bool

Check if a type is optional.

Parameters:

field (type) – The type to check.

Returns:

True if the type is optional, False otherwise.

Return type:

bool

fastapi2cli.utils.iter_api_routes(routes: Iterable[BaseRoute]) Iterator[APIRoute | RouteContext]

Yield every API route reachable from a list of routes, with resolved metadata.

Up to FastAPI 0.136, app.include_router copied the sub router’s routes into the parent application’s routes list, baking the accumulated prefix into route.path and merging the include time tags, dependencies and deprecated flag into the copy, so filtering app.routes on the route type was enough.

Starting with FastAPI 0.137 an included router is kept as an opaque wrapper and that include time state lives in a separate context instead of on the route. Reading the route directly therefore reports a router local path (/created instead of /api/outer/sub/created) and silently drops the router level tags, dependencies and deprecated flag, which would make every generated command request a non existing URL without its authentication headers. Walking with the route walker fastapi.openapi.utils.get_openapi itself uses resolves that context, so an included route is yielded as a proxy reporting the path and the metadata the application actually serves it under.

A route registered directly on the application has no such context, and is yielded unchanged as the very APIRoute object the application holds.

Entries that are not API routes are skipped: the generated documentation routes, websocket routes, and mounted sub applications, whose routes are served by another application. Routes hidden with include_in_schema=False are however still yielded – the application does serve them, so the command line interface exposes them too – which is why this walk is not simply the set of paths in the OpenAPI schema.

Parameters:

routes (Iterable[BaseRoute]) – The list of routes to walk (e.g. app.routes).

Returns:

An iterator over every reachable API route.

Return type:

Iterator[RouteLike]

Module contents

class fastapi2cli.AuthenticationResolverBase

Bases: object

Base class for authentication resolver.

This class provides default implementations for authentication resolver methods.

get_cookies() dict[str, Any]

Get cookies for authentication.

Returns:

A dictionary containing cookies.

Return type:

dict[str, Any]

get_headers() dict[str, Any]

Get headers for authentication.

Returns:

A dictionary containing headers.

Return type:

dict[str, Any]

get_query_parameters() dict[str, Any]

Get query parameters for authentication.

Returns:

A dictionary containing query parameters.

Return type:

dict[str, Any]

set_server_url(server_url: str)

Set the server url we are working on, useful for case where server_url is known only after parsing –server-url from cli. you should ignore this call if the authentication server is on a different server_url than the request one.

Parameters:

server_url (str) – the server_url to use for authentication

class fastapi2cli.BearerAuthResolver(token: str, scheme: str = 'Bearer')

Bases: StaticAuthResolver

Authentication resolver injecting a static Authorization bearer header.

Convenience resolver for the common case of a pre-issued API token. The token can be read from a config file and supplied once, so authenticated routes no longer prompt for it:

expose_app(app, server_url=config.SERVER_URL,
           authentication_resolver=BearerAuthResolver(config.TOKEN),
           authenticated_dependencies=[...])
Parameters:
  • token (str) – The token to send in the Authorization header.

  • scheme (str, optional) – The authorization scheme prefixing the token, defaults to “Bearer”.

class fastapi2cli.StaticAuthResolver(headers: dict[str, Any] = None, cookies: dict[str, Any] = None, query_parameters: dict[str, Any] = None)

Bases: AuthenticationResolverBase

Authentication resolver returning fixed, pre-configured credentials.

Use this when the credentials are already known (e.g. read from a config file) and don’t need to be negotiated with the server. Passing it to fastapi2cli.expose_app() injects the configured headers/cookies/query parameters on every authenticated request, so the user is never prompted for them.

Parameters:
  • headers (dict[str, Any], optional) – Headers to inject on authenticated requests, defaults to None.

  • cookies (dict[str, Any], optional) – Cookies to inject on authenticated requests, defaults to None.

  • query_parameters (dict[str, Any], optional) – Query parameters to inject on authenticated requests, defaults to None.

get_cookies() dict[str, Any]

Get the configured cookies.

Returns:

A copy of the configured cookies.

Return type:

dict[str, Any]

get_headers() dict[str, Any]

Get the configured headers.

Returns:

A copy of the configured headers.

Return type:

dict[str, Any]

get_query_parameters() dict[str, Any]

Get the configured query parameters.

Returns:

A copy of the configured query parameters.

Return type:

dict[str, Any]

fastapi2cli.expose_app(app: FastAPI, authentication_resolver: AuthenticationResolverBase = None, authenticated_dependencies: list[Callable] = None, request_executor: RequestExecutor = None, additional_parsers: dict[type, Callable[[str], Any]] = None, server_url: str = None, **kwargs: Any) Typer

Expose FastAPI application routes as a Typer CLI.

This function creates a Typer CLI based on the routes defined in a FastAPI application.

Parameters:
  • app (FastAPI) – The FastAPI application to expose.

  • authentication_resolver (AuthenticationResolverBase, optional) – Authentication resolver for the application, defaults to None. which will raise exception if attempting to access an authenticated route

  • authenticated_dependencies (list[Callable], optional) – List of authenticated dependencies, defaults to None. this allows the app to know what endpoint/route is considered as authenticated.

  • request_executor (RequestExecutor, optional) – Request executor for making HTTP requests, defaults to None.

  • additional_parsers (dict[type, Callable[[str], Any]], optional) – Additional parsers for custom types, defaults to None. This is for types that Typer don’t handle and are present in endpoints/routes you want to expose

  • server_url (str, optional) – The base URL of the server, defaults to None. (if set to none the cli server_url parameter will be mandatory)

  • kwargs (Any, optional) – extra arguments to provide to the generated commands as defaults

Returns:

Typer CLI exposing the FastAPI application routes.

Return type:

typer.Typer