fastapi2cli.web package

Submodules

fastapi2cli.web.authentication module

class fastapi2cli.web.authentication.AuthenticationManager(authenticated_dependencies: list[Callable], authentication_resolver: AuthenticationResolverBase)

Bases: object

Manager for authentication.

This class manages authentication for dependencies and routes.

property cookies: dict[str, Any]

Get cookies for authentication.

Returns:

A dictionary containing cookies.

Return type:

dict[str, Any]

property headers: dict[str, Any]

Get headers for authentication.

Returns:

A dictionary containing headers.

Return type:

dict[str, Any]

is_dependency_authenticated(dependency: Dependant)

Check if a dependency is authenticated.

A dependency counts as authenticated when it is a security scheme (what Security(...) and Depends(...) on a fastapi.security scheme resolve to), when it is one of the authenticated_dependencies declared when exposing the app, or when any dependency it itself depends on is.

The scheme is recognised through the resolved dependency’s call. FastAPI builds a Dependant for every entry of a dependency tree, so a fastapi.params.Security marker never appears in it, and testing for one silently reported every route as unauthenticated – sending the request without its credentials.

Parameters:

dependency (Dependant) – The dependency to check.

Returns:

True if the dependency is authenticated, False otherwise.

Return type:

bool

is_route_authenticated(route: APIRoute | RouteContext) bool

Check if a route is authenticated.

Parameters:

route (RouteLike) – The route to check.

Returns:

True if the route is authenticated, False otherwise.

Return type:

bool

property 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) None

set the server url for the authentication_resolver using the same server_url as the request. Called for each request.

Parameters:

server_url (str) – the server_url to use for authentication

class fastapi2cli.web.authentication.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.web.authentication.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.web.authentication.NoAuthResolver

Bases: AuthenticationResolverBase

Authentication resolver for no authentication.

This class provides an implementation for authentication resolver methods when no authentication is required.

get_cookies() dict[str, Any]

Get cookies for authentication.

Raises:

NoAuthResolverException – Always raised since no authentication cookies are available.

get_headers() dict[str, Any]

Get headers for authentication.

Raises:

NoAuthResolverException – Always raised since no authentication headers are available.

get_query_parameters() dict[str, Any]

Get query parameters for authentication.

Raises:

NoAuthResolverException – Always raised since no authentication query parameters are available.

exception fastapi2cli.web.authentication.NoAuthResolverException

Bases: Exception

Exception raised when authentication resolver is not available.

This exception is raised when attempting to access authenticated resources but no authentication resolver are provided.

class fastapi2cli.web.authentication.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.web.parameters module

fastapi2cli.web.parameters.PATH_PARAMETER_PATTERN = re.compile('{([^{}:]+)(:[^{}]+)?}')

A path placeholder in route.path, with the optional Starlette converter that follows its name.

/files/{file_path:path} holds the name file_path and the converter :path. The converter has to be matched too: it is part of the placeholder to replace, and str.format would otherwise read it as a format specifier and raise ValueError: Invalid format specifier.

fastapi2cli.web.parameters.get_body(route: APIRoute | RouteContext, **http_parameters: Any) BaseModel | None

Get the body parameters for a given route.

This function retrieves the body parameters for a given route from the provided HTTP parameters.

Parameters:
  • route (RouteLike) – The route for which to retrieve the body parameters.

  • http_parameters (Any) – HTTP parameters to retrieve the body parameters from.

Returns:

The body parameters.

Return type:

BaseModel | None

Get the cookie parameters for a given route.

This function retrieves the cookie parameters for a given route from the provided HTTP parameters.

Parameters:
  • route (RouteLike) – The route for which to retrieve the cookie parameters.

  • http_parameters (Any) – HTTP parameters to retrieve the cookie parameters from.

Returns:

The cookie parameters.

Return type:

dict[str, Any]

fastapi2cli.web.parameters.get_formatted_url(url: str, route: APIRoute | RouteContext, **http_parameters: Any) str

Get the formatted URL for a given route.

This function formats the URL for a given route with the provided HTTP parameters.

The route path is appended to the whole of the base URL, so a server mounted under a prefix (https://example.com/api) keeps that prefix. Joining the two as absolute URLs would instead replace it, and request a path the server does not serve.

Path parameter values are percent encoded, so a value holding /, ? or # stays a single path segment instead of rewriting the path or the query string of the request. The one exception is a :path converted parameter, which is declared precisely to span segments.

Parameters:
  • url (str) – The base URL to format.

  • route (RouteLike) – The route for which to format the URL.

  • http_parameters (Any) – HTTP parameters to use for formatting the URL.

Returns:

The formatted URL.

Return type:

str

Raises:

KeyError – If the path holds a placeholder the route declares no parameter for.

fastapi2cli.web.parameters.get_header_parameters(route: APIRoute | RouteContext, **http_parameters: Any) dict[str, Any]

Get the header parameters for a given route.

This function retrieves the header parameters for a given route from the provided HTTP parameters.

Parameters:
  • route (RouteLike) – The route for which to retrieve the header parameters.

  • http_parameters (Any) – HTTP parameters to retrieve the header parameters from.

Returns:

The header parameters.

Return type:

dict[str, Any]

fastapi2cli.web.parameters.get_parameter_value(parameter_name: str, field_info: FieldInfo, **http_parameters: Any) Any

Get the value of a parameter from HTTP parameters.

This function retrieves the value of a parameter from the provided HTTP parameters. It checks whether the parameter is required, and if not provided, it returns the default value defined in the field info.

Parameters:
  • parameter_name (str) – The name of the parameter to get the value of.

  • field_info (FieldInfo) – Information about the parameter field.

  • http_parameters (Any) – HTTP parameters to retrieve the value from.

Returns:

The value of the parameter.

Return type:

Any

Raises:

KeyError – If a required parameter is missing in the HTTP parameters.

fastapi2cli.web.parameters.get_parameter_value_for_object(type_: type[BaseModel], field_name: str, **http_parameters: Any)

Get the value of a parameter for an object.

This function retrieves the value of a parameter for a given object type from the provided HTTP parameters. It constructs the properties of the object using the parameter values.

Parameters:
  • type (type[BaseModel]) – The type of the object to retrieve the parameter value for.

  • field_name (str) – The name of the field. (used for searching object properties values from http parameters)

  • http_parameters (Any) – HTTP parameters to retrieve the value of properties of the object from. (expected nested names)

Returns:

An instance of the object type with the retrieved properties.

Return type:

BaseModel

fastapi2cli.web.parameters.get_parameters_values(parameter_definitions: dict[str, ~pydantic.fields.FieldInfo], serializer: ~typing.Callable[[~typing.Any], ~typing.Any] = <function serialize_parameter_value>, keep_none: bool = False, **http_parameters: ~typing.Any) dict[str, Any]

Get the values of parameters from HTTP parameters.

This function retrieves the values of parameters defined by the given parameter definitions from the provided HTTP parameters.

Parameters are looked up under their python name and returned under their wire name (field_info.alias when there is one), which is what a Header holding an underscore or an explicitly aliased Query is served as.

Parameters:
  • parameter_definitions (dict[str, FieldInfo]) – Definitions of parameters to retrieve values for.

  • serializer (Callable[[Any], Any], optional) – How to turn a value into its wire representation, defaults to serialize_parameter_value().

  • keep_none (bool, optional) – Whether to keep parameters resolving to None, defaults to False. An optional parameter the user did not provide resolves to None, which is not a value the server can be sent: as a query parameter it arrives as the empty string, making a non str parameter fail validation, and as a header it is rejected outright by the HTTP client. Leaving it out is what makes the server apply the default it declared. Path parameters are the exception, as every placeholder in the path has to be substituted.

  • http_parameters (Any) – HTTP parameters to retrieve values from.

Returns:

The values of the parameters.

Return type:

dict[str, Any]

fastapi2cli.web.parameters.get_query_parameters(route: APIRoute | RouteContext, **http_parameters: Any) dict[str, Any]

Get the query parameters for a given route.

This function retrieves the query parameters for a given route from the provided HTTP parameters.

Parameters:
  • route (RouteLike) – The route for which to retrieve the query parameters.

  • http_parameters (Any) – HTTP parameters to retrieve the query parameters from.

Returns:

The query parameters.

Return type:

dict[str, Any]

fastapi2cli.web.parameters.serialize_header_value(value: Any) Any

Serialize a header or cookie value into a string.

Unlike query parameters, headers and cookies carry no type information: an HTTP client requires a string and raises TypeError on anything else. Booleans are lowercased to the true/false spelling the server parses rather than the python one.

Containers are left untouched: a list valued header means a repeated header, which a single name to value mapping cannot express, and stringifying it would silently send a python repr.

Parameters:

value (Any) – The value to serialize.

Returns:

The string representation of the value, or the value itself when it is not a scalar.

Return type:

Any

fastapi2cli.web.parameters.serialize_parameter_value(value: Any) Any

Serialize a parameter value into what should be sent over the wire.

str(value) is not the wire representation of every type an endpoint can declare: it renders an Enum member as Color.RED rather than as its value red, and a datetime with a space instead of the ISO 8601 T separator. Pydantic’s JSON serialization is the one FastAPI validates the incoming request against, so it round trips.

Parameters:

value (Any) – The value to serialize.

Returns:

The JSON compatible representation of the value.

Return type:

Any

fastapi2cli.web.server_interactor module

fastapi2cli.web.server_interactor.METHOD_PREFERENCE = ('GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS')

Which method to call a route with when it is registered under several of them.

route.methods is a set, so picking its first element makes the method the command sends depend on the hash seed of the interpreter, i.e. it varies between runs of the very same CLI. A route almost always declares a single method; when it declares more, this order settles on one deterministically, preferring the safe GET over one that mutates state.

class fastapi2cli.web.server_interactor.RequestExecutor(*args, **kwargs)

Bases: Protocol

A protocol representing an HTTP request executor.

This protocol defines the structure of an object that can execute HTTP requests.

request(method: str, url: str, params: dict[str, Any], headers: dict[str, Any], cookies: dict[str, Any], json: dict[str, Any] | None) Response

Execute an HTTP request.

Parameters:
  • method (str) – The HTTP method to use for the request.

  • url (str) – The URL to send the request to.

  • params (dict[str, Any]) – The query parameters for the request.

  • headers (dict[str, Any]) – The headers for the request.

  • cookies (dict[str, Any]) – The cookies for the request.

  • json (dict[str, Any] | None) – The JSON payload for the request.

Returns:

The response to the request.

Return type:

Response

class fastapi2cli.web.server_interactor.ServerInteractor(server_url: str, request_executor: RequestExecutor, authentication_manager: AuthenticationManager)

Bases: object

Interacts with the server by sending requests and handling responses.

This class provides methods to interact with the server by sending requests and handling responses. It uses a request executor to send HTTP requests and an authentication manager to manage authentication.

get_response(route: APIRoute | RouteContext, **http_parameters: Any) Response

Get the response from the server for a given route.

This method constructs the URL, parameters, headers, and cookies for the request based on the route and provided HTTP parameters. It then sends the request using the request executor and returns the response.

Parameters:
  • route (RouteLike) – The route for which to get the response.

  • http_parameters (Any) – The HTTP parameters for the request.

Returns:

The response from the server.

Return type:

Response

request(route: APIRoute | RouteContext, **http_parameters: Any) T | list[T] | None

Send a request to the server and handle the response.

This method sends a request to the server for the given route with the provided HTTP parameters. It then handles the response based on the route’s response model.

A response with no body (a 204 No Content for instance) yields None, and a route declaring no response model yields the decoded JSON as is. Any other response model is validated with pydantic, so a route annotated with a plain type (-> dict, -> list[str], -> str) is handled like one annotated with a model rather than rejected. FastAPI refuses at registration time a response model pydantic cannot build a validator for, so this validation cannot fail to be built here.

Parameters:
  • route (RouteLike) – The route for which to send the request.

  • http_parameters (Any) – The HTTP parameters for the request.

Returns:

The response from the server.

Return type:

T | list[T] | None

Raises:

httpx.HTTPStatusError – If the server answered with an error status.

fastapi2cli.web.server_interactor.get_method(route: APIRoute | RouteContext) str

Get the HTTP method to call a route with.

Parameters:

route (RouteLike) – The route to get the method of.

Returns:

The preferred method among the ones the route is registered under.

Return type:

str

Module contents