mautrix.api

class mautrix.api.APIPath

Bases: enum.Enum

The known Matrix API path prefixes. These don’t start with a slash so they can be used nicely with yarl.

CLIENT = '_matrix/client'
MEDIA = '_matrix/media'
SYNAPSE_ADMIN = '_synapse/admin'
class mautrix.api.Method

Bases: enum.Enum

A HTTP method.

GET = 'GET'
POST = 'POST'
PUT = 'PUT'
DELETE = 'DELETE'
PATCH = 'PATCH'
class mautrix.api.PathBuilder

Bases: object

A utility class to build API paths.

Examples

>>> from mautrix.api import Path
>>> room_id = "!foo:example.com"
>>> event_id = "$bar:example.com"
>>> str(Path.v3.rooms[room_id].event[event_id])
"_matrix/client/v3/rooms/%21foo%3Aexample.com/event/%24bar%3Aexample.com"
__init__(path='')
Parameters

path (str | mautrix.api.APIPath) –

Return type

None

raw(append)

Directly append a string to the path.

Parameters

append (str) – The string to append.

Return type

mautrix.api.PathBuilder

replace(find, replace)
Parameters
  • find (str) –

  • replace (str) –

Return type

mautrix.api.PathBuilder

mautrix.api.ClientPath

A path builder with the standard client prefix ( /_matrix/client, APIPath.CLIENT).

mautrix.api.Path

A shorter alias for ClientPath

mautrix.api.MediaPath

A path builder with the standard media prefix (/_matrix/media, APIPath.MEDIA)

Examples

>>> from mautrix.api import MediaPath
>>> str(MediaPath.v3.config)
"_matrix/media/v3/config"
mautrix.api.SynapseAdminPath

A path builder for synapse-specific admin API paths (/_synapse/admin, APIPath.SYNAPSE_ADMIN)

Examples

>>> from mautrix.api import SynapseAdminPath
>>> user_id = "@user:example.com"
>>> str(SynapseAdminPath.v1.users[user_id]/login)
"_synapse/admin/v1/users/%40user%3Aexample.com/login"
class mautrix.api.HTTPAPI

Bases: object

HTTPAPI is a simple asyncio Matrix API request sender.

default_ua: ClassVar[str] = 'mautrix-python/0.20.6 aiohttp/3.8.1 Python/3.10.0'

The default value for the User-Agent header.

You should prepend your program name and version here before creating any HTTPAPI instances in order to have proper user agents for all requests.

global_default_retry_count: ClassVar[int] = 0

The default retry count to use if an instance-specific value is not passed.

__init__(base_url, token='', *, client_session=None, default_retry_count=None, txn_id=0, log=None, loop=None, as_user_id=None, as_device_id=None)
Parameters
  • base_url (URL | str) – The base URL of the homeserver’s client-server API to use.

  • token (str) – The access token to use.

  • client_session (ClientSession) – The aiohttp client session to use.

  • txn_id (int) – The outgoing transaction ID to start with.

  • log (TraceLogger | None) – The logging.Logger instance to log requests with.

  • default_retry_count (int) – Default number of retries to do when encountering network errors.

  • as_user_id (UserID | None) – An optional user ID to set as the user_id query parameter for appservice requests.

  • as_device_id (UserID | None) – An optional device ID to set as the user_id query parameter for appservice requests (MSC3202).

  • loop (asyncio.AbstractEventLoop | None) –

Return type

None

base_url: URL

The base URL of the homeserver’s client-server API to use.

token: str

The access token to use in requests.

log: TraceLogger

The logging.Logger instance to log requests with.

session: ClientSession

The aiohttp ClientSession instance to make requests with.

as_user_id: UserID | None

An optional user ID to set as the user_id query parameter for appservice requests.

as_device_id: DeviceID | None

An optional device ID to set as the user_id query parameter for appservice requests (MSC3202).

txn_id: int | None

A counter used for generating transaction IDs.

default_retry_count: int

The default retry count to use if a custom value is not passed to request()

log_download_request(url, query_params)
Parameters
Return type

int

log_download_request_done(url, req_id, duration, status)
Parameters
Return type

None

async request(method, path, content=None, headers=None, query_params=None, retry_count=None, metrics_method='', min_iter_size=26214400, sensitive=False)

Make a raw Matrix API request.

Parameters
  • method (Method) – The HTTP method to use.

  • path (PathBuilder | str) – The full API endpoint to call (including the _matrix/… prefix)

  • content (dict | list | bytes | bytearray | str | AsyncBody | None) – The content to post as a dict/list (will be serialized as JSON) or bytes/str (will be sent as-is).

  • headers (dict[str, str] | None) – A dict of HTTP headers to send. If the headers don’t contain Content-Type, it’ll be set to application/json. The Authorization header is always overridden if token is set.

  • query_params (Mapping[str, str] | None) – A dict of query parameters to send.

  • retry_count (int | None) – Number of times to retry if the homeserver isn’t reachable. Defaults to default_retry_count.

  • metrics_method (str) – Name of the method to include in Prometheus timing metrics.

  • min_iter_size (int) – If the request body is larger than this value, it will be passed to aiohttp as an async iterable to stop it from copying the whole thing in memory.

  • sensitive (bool) – If True, the request content will not be logged.

Returns

The parsed response JSON.

Return type

JSON

get_txn_id()

Get a new unique transaction ID.

Return type

str

get_download_url(mxc_uri, download_type='download', file_name=None, authenticated=False)

Get the full HTTP URL to download a mxc:// URI.

Parameters
  • mxc_uri (str) – The MXC URI whose full URL to get.

  • download_type (Literal['download', 'thumbnail']) – The type of download (“download” or “thumbnail”).

  • file_name (Optional[str]) – Optionally, a file name to include in the download URL.

  • authenticated (bool) – Whether to use the new authenticated download endpoint in Matrix v1.11.

Returns

The full HTTP URL.

Raises

ValueError – If mxc_uri doesn’t begin with mxc://.

Return type

yarl.URL

Examples

>>> api = HTTPAPI(base_url="https://matrix-client.matrix.org", ...)
>>> api.get_download_url("mxc://matrix.org/pqjkOuKZ1ZKRULWXgz2IVZV6")
"https://matrix-client.matrix.org/_matrix/media/v3/download/matrix.org/pqjkOuKZ1ZKRULWXgz2IVZV6"
>>> api.get_download_url("mxc://matrix.org/pqjkOuKZ1ZKRULWXgz2IVZV6", file_name="hello.png")
"https://matrix-client.matrix.org/_matrix/media/v3/download/matrix.org/pqjkOuKZ1ZKRULWXgz2IVZV6/hello.png"
static parse_mxc_uri(mxc_uri)

Parse a mxc:// URI.

Parameters

mxc_uri (str) – The MXC URI to parse.

Returns

A tuple containing the server and media ID of the MXC URI.

Raises

ValueError – If mxc_uri doesn’t begin with mxc://.

Return type

tuple[str, str]