MTX API PY
Python SDK (wrapper) to consume the MTX API.
Installation
pip install mtx-api-py
Quick start
import asyncio
from mtx_api import MTXClient
async def main():
async with MTXClient(
base_url="https://api.mtx.example.com",
client_id="<YOUR_CLIENT_ID>",
jwt_secret="<BASE64_SECRET>", # optional; only if you will use auth.login_jwt
) as client:
ok = await client.base.status(access_token="<ACCESS_TOKEN>")
print(ok)
asyncio.run(main())
Configure via environment variables
Each MTXClient argument left out is read from its environment variable. The SDK does not read .env files: load
yours first, for example with load_dotenv() from python-dotenv as in the example below.
# .env
MTX_BASE_URL=https://api.mtx.example.com
MTX_CLIENT_ID=<YOUR_CLIENT_ID>
MTX_JWT_SECRET=<BASE64_SECRET> # Optional: only needed if you will use login_jwt
MTX_OPEN_ID_AUTH_URL=<AUTH_URL> # Optional: only needed for the OpenID login
MTX_OPEN_ID_CLIENT_KEY=<CLIENT_KEY> # Optional: only needed for the OpenID login
MTX_APP_KEY=<YOUR_APP_KEY> # Optional: numeric key of your MTX application, sent as app_key
MTX_REDACT_LOGS=false # Optional: show secrets and personal data in debug logs
MTX_TIMEOUT=60 # Optional: seconds each call waits for the platform
The SDK logs each call on logger mtx_logs: the method and path at INFO, and a curl-style line and the response,
error responses included, at DEBUG. It raises errors without logging them, so your application decides whether and
how to log each one. Set its level with logging.getLogger("mtx_logs").setLevel(...).
Debug logs mask secrets and personal data, such as emails, names and phones: the value of every header or field
named in SENSITIVE_LOG_KEYS is replaced by the REDACTED placeholder, and so is, in what the SDK sends, every field
or query parameter named in SENSITIVE_REQUEST_KEYS, which adds the codes the user types (all three constants in
mtx_api/client/_mtx_http_client.py). Disable it with MTX_REDACT_LOGS=false or MTXClient(redact_logs=False); it
only changes what is logged, never what is sent. The SDK leaves the httpx logger as your application configures it;
at INFO it logs the method, URL and status of each call.
import asyncio
from mtx_api import MTXClient
from dotenv import load_dotenv
load_dotenv() # Load environment variables from .env
async def main():
async with MTXClient() as client:
ok = await client.base.status(access_token="<ACCESS_TOKEN>")
print(ok)
asyncio.run(main())
Development
Install hatch, then run the checks and tests with hatch run dev:tests. Every command and
convention of the repository is in AGENTS.md, at its root.
MTX Client Reference
All available functions accept their parameters as keyword arguments.
You can omit arguments that are not needed and accept None.
Each function's Effect says what it changes on the platform, and effect_of(client.requests.create) returns it as
an OperationEffect: read_only changes nothing, additive adds without changing or removing what exists, and
destructive changes or removes what exists.
MTXClient
Asynchronous client of the MTX platform.
Each attribute groups the operations on one resource; get_documentation() describes them all. Each operation
says when to call it; this text says only how they fit together.
A jurisdiction, identified by its code, offers services, and each request belongs to one of its services. The
client keeps no session: a login returns the user's tokens, and each operation on the user's behalf takes their
access token.
To create a request, call services.list to choose the service, services.detail for its questions, which the
additional_data operations help answer, services.validate_position, location.resolve and
requests.find_duplicates with the chosen position, and then requests.create.
Constructor
Signature
MTXClient(*, base_url: 'str | None' = None, client_id: 'str | None' = None, app_key: 'int | None' = None, jwt_secret: 'str | None' = None, open_id_auth_url: 'str | None' = None, open_id_client_key: 'str | None' = None, timeout: 'float | None' = None, redact_logs: 'bool | None' = None, transport: 'httpx.AsyncBaseTransport | None' = None)
Docstring
Creates a client of the MTX platform.
Every argument left out is read from its MTX_* environment variable; an argument passed here wins over
the variable. Use the client as an async context manager, so its connections close when the block ends.
Args:
- base_url (str, optional): Optional base URL of the platform, such as
https://api.example.com.
If not provided, it is read from MTX_BASE_URL; one of the two is required. Defaults to None.
- client_id (str, optional): Optional identifier of the application on the platform, sent with every
operation. If not provided, it is read from
MTX_CLIENT_ID; one of the two is required.
Defaults to None.
- app_key (int, optional): Optional numeric key of the application, sent by
jurisdictions.list and
jurisdictions.detail; when set, jurisdictions.list returns only that application's
jurisdictions. If not provided, it is read from MTX_APP_KEY. Defaults to None.
- jwt_secret (str, optional): Optional standard base64 secret that
auth.login_jwt signs its tokens
with; no other operation uses it. If not provided, it is read from MTX_JWT_SECRET.
Defaults to None.
- open_id_auth_url (str, optional): Optional authorization URL of the platform's identity provider,
where the user signs in for
auth.open_id_login_start; no other operation uses it. If not
provided, it is read from MTX_OPEN_ID_AUTH_URL. Defaults to None.
- open_id_client_key (str, optional): Optional client identifier the application registered with the
identity provider, with the out-of-band redirect URI; it also selects the platform's
configuration for that provider, and the OpenID login needs it. If not provided, it is read
from
MTX_OPEN_ID_CLIENT_KEY. For an application with several identity providers, create one
client per provider. Defaults to None.
- timeout (float, optional): Optional number of seconds each operation waits for the platform before
it fails. If not provided, it is read from
MTX_TIMEOUT, and it is 30 when neither is set.
Defaults to None.
- redact_logs (bool, optional): Optional. Whether the debug logs mask secrets and personal data;
False shows them. It changes only what is logged, never what is sent. If not provided, it is read
from
MTX_REDACT_LOGS, and logs are masked when neither is set. Defaults to None.
- transport (httpx.AsyncBaseTransport, optional): Optional transport for the client's connections,
such as
httpx.MockTransport to simulate the platform in tests. If not provided, the client
connects to base_url. Defaults to None.
additional_data
external_answers
Effect: read_only
Signature
additional_data.external_answers(*, access_token: 'str | None' = None, question_id: 'str', variables: 'Mapping[str, str] | None' = None, query: 'str | None' = None, page: 'int | None' = None, limit: 'int | None' = None) -> 'PossibleAnswerList'
Docstring
List the answer options of an externalSingleValueList or externalMultiValueList question.
The options of an external question come from a system outside the platform and
may depend on the values of the question's required_variables. When that list is
empty, call this tool without variables; otherwise call it only when every required
variable has a value, and call it again when one of those values changes. When
exactly one option is returned, select it without asking the user, since other
external questions may need its value as a variable.
Args:
- access_token (str, optional): Optional token used for authentication. If not provided, the operation
will be made without authentication. Defaults to None.
- question_id (str): The unique identifier of the external question.
- variables (Mapping[str, str], optional): Optional values of the question's
required_variables, by name. Each name is either a known value (lat, lng,
service_name, level, jurisdiction_id or jurisdiction_element_id) or the id of
another question, whose value is the answer given to it. Defaults to None.
- query (str, optional): Optional case-insensitive text to look for in the option values.
It only filters the options of the requested page, so a page can come back
shorter or empty while later pages still have matches. Defaults to None.
- page (int, optional): Optional page number, starting at 1. Defaults to None.
- limit (int, optional): Optional number of options per page, at most 90.
Defaults to None.
Returns:
- PossibleAnswerList: The options of the requested page, empty after the last page.
external_questions
Effect: read_only
Signature
additional_data.external_questions(*, access_token: 'str | None' = None, question_list_id: 'str', variables: 'Mapping[str, str]') -> 'AdditionalDataAnswerList'
Docstring
Get the answers that the platform fills in from an external system for a question list.
Use this tool when the required_variables of a service's additional_data is not
empty. The platform asks the external system for the questions that have a
response_attribute and returns them already answered; send those answers in the
additional_data of requests.create.
Args:
- access_token (str, optional): Optional token used for authentication. If not provided, the operation
will be made without authentication. Defaults to None.
- question_list_id (str): The unique identifier of the question list, the
id of the
service's additional_data.
- variables (Mapping[str, str]): Values of every name in the question list's
required_variables; the operation fails when one is missing. Each name is
either a known value (lat, lng, service_name, level, jurisdiction_id or
jurisdiction_element_id) or the id of a question, whose value is the answer
given to it.
Returns:
- AdditionalDataAnswerList: The answers filled in, each with its question, value and
whether it is required and editable.
list_answers
Effect: read_only
Signature
additional_data.list_answers(*, access_token: 'str | None' = None, question_id: 'str', page: 'int | None' = None, limit: 'int | None' = None) -> 'PossibleAnswerList'
Docstring
List the answer options of a massiveSingleValueList question, one page at a time.
A massiveSingleValueList question can have thousands of options, and the service
detail only includes the first ones. Use this tool to browse the rest in order; to
find an option from what the user said, use additional_data.search_answers instead.
Args:
- access_token (str, optional): Optional token used for authentication. If not provided, the operation
will be made without authentication. Defaults to None.
- question_id (str): The unique identifier of the massiveSingleValueList question.
- page (int, optional): Optional page number, starting at 1. Defaults to None.
- limit (int, optional): Optional number of options per page, at most 10: the platform
returns 10 options for a higher value but skips that many options when moving
to the next page. Defaults to None.
Returns:
- PossibleAnswerList: The options of the requested page, empty after the last page.
search_answers
Effect: read_only
Signature
additional_data.search_answers(*, access_token: 'str | None' = None, question_id: 'str', query: 'str', page: 'int | None' = None, limit: 'int | None' = None) -> 'PossibleAnswerList'
Docstring
Search the answer options of a massiveSingleValueList question by text.
Use this tool to find the option that matches what the user said, since the service
detail only includes the first options of a massiveSingleValueList question. The
match is case-insensitive and looks for the text anywhere in the option value.
Args:
- access_token (str, optional): Optional token used for authentication. If not provided, the operation
will be made without authentication. Defaults to None.
- question_id (str): The unique identifier of the massiveSingleValueList question.
- query (str): Text to look for in the option values. An empty text matches every option.
- page (int, optional): Optional page number, starting at 1. Defaults to None.
- limit (int, optional): Optional number of options per page, at most 90.
Defaults to None.
Returns:
- PossibleAnswerList: The matching options of the requested page, empty when none match.
upload_file
Effect: additive
Signature
additional_data.upload_file(*, access_token: 'str | None' = None, file: 'tuple[str, bytes]') -> 'str'
Docstring
Upload a file and get the URL to answer a media question with.
Use this tool when the user provides the file for an image, imageGallery, signature,
videoClip or audioClip question of a service's additional_data: send the returned URL
as the answer's value in requests.create (one URL per image for imageGallery). A file
already published at a URL needs no upload. The platform accepts images (JPEG, PNG, GIF,
TIFF, BMP, SVG or ICO), MP4 video and MP3 or WAV audio, and rejects a file whose content
does not match its extension.
Args:
- access_token (str, optional): Optional token used for authentication. If not provided, the operation
will be made without authentication. Defaults to None.
- file (tuple[str, bytes]): A tuple containing the file name (str) and the file content (bytes).
The file name must include an extension and the content must not be empty.
Returns:
- str: The URL of the uploaded file.
auth
confirm_two_factor
Effect: additive
Signature
auth.confirm_two_factor(*, two_factor_hash: str, code: str) -> mtx_api.models.auth.Authentication
Docstring
Completes a login that requires a second factor, with the code the user received by email.
Call it when auth.login raises TwoFactorRequiredError, with that error's
two_factor_hash and the 4-digit code the platform emailed the user. The code is valid for
one day and allows 3 attempts: the platform rejects a wrong code, and after the third wrong
one, or once the code expires, it no longer finds the login, which must start again with
auth.login.
Args:
- two_factor_hash (str): The
two_factor_hash of the TwoFactorRequiredError raised by
auth.login.
- code (str): The 4-digit code the user received by email.
Returns:
- Authentication: A model containing access and refresh tokens.
generate_biotoken
Effect: destructive
Signature
auth.generate_biotoken(*, access_token: str, device_id: str) -> mtx_api.models.auth.BioToken
Docstring
Generates the biotoken that logs the user back in on this device without their password.
Use this tool after a login, when the user wants to log in again on this device without
their credentials, for example once their refresh token expires. Each user has one
biotoken per device: generating another one for the same device replaces it. Store it on
the device and never show it.
Args:
- access_token (str): Token of the user the biotoken logs in.
- device_id (str): A stable and unique identifier for the device that stores the biotoken.
Returns:
- BioToken: The biotoken and a greeting with the user's first name.
login
Effect: additive
Signature
auth.login(*, username: str, password: str) -> mtx_api.models.auth.Authentication
Docstring
Authenticates a user using their username (email) and password.
Use this tool for standard user login to obtain access credentials. When the platform
requires a second factor, the login raises TwoFactorRequiredError and the platform emails
the user a 4-digit code: ask the user for it and call auth.confirm_two_factor with the
error's two_factor_hash. The platform rejects that login when the user has no confirmed
email.