App registration, authentication and preferences

Before you can use the Mastodon API, you have to register your application (which gets you a client key and client secret) and then log in (which gets you an access token) and out (revoking the access token you are logged in with). These functions allow you to do those things. Additionally, it is also possible to programmatically register a new user.

For convenience, once you have a client id, secret and access token, you can simply pass them to the constructor of the class, too!

Note that while it is perfectly reasonable to log back in whenever your app starts, registering a new application on every startup is not, so don’t do that - instead, register an application once, and then persist your client id and secret. A convenient method for this is provided by the functions dealing with registering the app, logging in and the Mastodon classes constructor.

App registration and information

static Mastodon.create_app(client_name, scopes: List[str] = ['read', 'write', 'follow', 'push'], redirect_uris: str | List[str] | None = None, website: str | None = None, to_file: str | PurePath | None = None, api_base_url: str | None = None, request_timeout: float = 300, session: Session | None = None, user_agent: str = 'mastodonpy') Tuple[str, str][source]

Create a new app with given client_name and scopes (The basic scopes are “read”, “write”, “follow” and “push” - more granular scopes are available, please refer to Mastodon documentation for which) on the instance given by api_base_url.

Specify redirect_uris if you want users to be redirected to a certain page after authenticating in an OAuth flow. You can specify multiple URLs by passing a list. Note that if you wish to use OAuth authentication with redirects, the redirect URI must be one of the URLs specified here.

Specify to_file to persist your app’s info to a file so you can use it in the constructor. Specify website to give a website for your app.

Specify session with a requests.Session for it to be used instead of the default. This can be used to, amongst other things, adjust proxy or SSL certificate settings.

Specify user_agent if you want to use a specific name as User-Agent header, otherwise “mastodonpy” will be used.

Presently, app registration is open by default, but this is not guaranteed to be the case for all Mastodon instances in the future.

Returns client_id and client_secret, both as strings.

Mastodon.app_verify_credentials() Application[source]

Fetch information about the current application.

Added: Mastodon v2.0.0, last changed: Mastodon v2.7.2

Authentication

Mastodon.__init__(client_id: str | PurePath | None = None, client_secret: str | None = None, access_token: str | PurePath | None = None, api_base_url: str | None = None, debug_requests: bool = False, ratelimit_method: str = 'wait', ratelimit_pacefactor: float = 1.1, request_timeout: float = 300, mastodon_version: str | None = None, version_check_mode: str = 'created', session: Session | None = None, feature_set: str = 'mainline', user_agent: str = 'mastodonpy', lang: str | None = None)[source]

Create a new API wrapper instance based on the given client_secret and client_id on the instance given by api_base_url. If you give a client_id and it is not a file, you must also give a secret. If you specify an access_token then you don’t need to specify a client_id. It is allowed to specify neither - in this case, you will be restricted to only using endpoints that do not require authentication. If a file is given as client_id, client ID, secret and base url are read from that file.

You can also specify an access_token, directly or as a file (as written by log_in()). If a file is given, Mastodon.py also tries to load the base URL from this file, if present. A client id and secret are not required in this case.

Mastodon.py can try to respect rate limits in several ways, controlled by ratelimit_method. “throw” makes functions throw a MastodonRatelimitError when the rate limit is hit. “wait” mode will, once the limit is hit, wait and retry the request as soon as the rate limit resets, until it succeeds. “pace” works like throw, but tries to wait in between calls so that the limit is generally not hit (how hard it tries to avoid hitting the rate limit can be controlled by ratelimit_pacefactor). The default setting is “wait”. Note that even in “wait” and “pace” mode, requests can still fail due to network or other problems! Also note that “pace” and “wait” are NOT thread safe.

By default, a timeout of 300 seconds is used for all requests. If you wish to change this, pass the desired timeout (in seconds) as request_timeout.

For fine-tuned control over the requests object use session with a requests.Session.

The mastodon_version parameter can be used to specify the version of Mastodon that Mastodon.py will expect to be installed on the server. The function will throw an error if an unparseable Version is specified. If no version is specified, Mastodon.py will set mastodon_version to the detected version.

The version check mode can be set to “created” (the default behaviour), “changed” or “none”. If set to “created”, Mastodon.py will throw an error if the version of Mastodon it is connected to is too old to have an endpoint. If it is set to “changed”, it will throw an error if the endpoint’s behaviour has changed after the version of Mastodon that is connected has been released. If it is set to “none”, version checking is disabled.

feature_set can be used to enable behaviour specific to non-mainline Mastodon API implementations. Details are documented in the functions that provide such functionality. Currently supported feature sets are mainline, fedibird and pleroma.

For some Mastodon instances a User-Agent header is needed. This can be set by parameter user_agent. Starting from Mastodon.py 1.5.2 create_app() stores the application name into the client secret file. If client_id points to this file, the app name will be used as User-Agent header as default. It is possible to modify old secret files and append a client app name to use it as a User-Agent name.

lang can be used to change the locale Mastodon will use to generate responses. Valid parameters are all ISO 639-1 (two letter) or for a language that has none, 639-3 (three letter) language codes. This affects some error messages (those related to validation) and trends. You can change the language using set_language().

If no other User-Agent is specified, “mastodonpy” will be used.

Mastodon.log_in(username: str | None = None, password: str | None = None, code: str | None = None, redirect_uri: str = 'urn:ietf:wg:oauth:2.0:oob', refresh_token: str | None = None, scopes: List[str] = ['read', 'write', 'follow', 'push'], to_file=typing.Union[str, pathlib.PurePath]) str[source]

Get the access token for a user.

The username is the email address used to log in into Mastodon.

Can persist access token to file to_file, to be used in the constructor.

Handles password and OAuth-based authorization.

Will throw a MastodonIllegalArgumentError if the OAuth flow data or the username / password credentials given are incorrect, and MastodonAPIError if all of the requested scopes were not granted.

For OAuth 2, obtain a code via having your user go to the URL returned by auth_request_url() and pass it as the code parameter. In this case, make sure to also pass the same redirect_uri parameter as you used when generating the auth request URL. If passing code`you should not pass `username or password.

Returns the access token as a string.

Mastodon.auth_request_url(client_id: str | PurePath | None = None, redirect_uris: str = 'urn:ietf:wg:oauth:2.0:oob', scopes: List[str] = ['read', 'write', 'follow', 'push'], force_login: bool = False, state: str | None = None, lang: str | None = None) str[source]

Returns the URL that a client needs to request an OAuth grant from the server.

To log in with OAuth, send your user to this URL. The user will then log in and get a code which you can pass to log_in().

scopes are as in log_in(), redirect_uris is where the user should be redirected to after authentication. Note that redirect_uris must be one of the URLs given during app registration, and that despite the plural-like name, you only get to use one here. When using urn:ietf:wg:oauth:2.0:oob, the code is simply displayed, otherwise it is added to the given URL as the “code” request parameter.

Pass force_login if you want the user to always log in even when already logged into web Mastodon (i.e. when registering multiple different accounts in an app).

state is the oauth state parameter to pass to the server. It is strongly suggested to use a random, nonguessable value (i.e. nothing meaningful and no incrementing ID) to preserve security guarantees. It can be left out for non-web login flows.

Pass an ISO 639-1 (two letter) or, for languages that do not have one, 639-3 (three letter) language code as lang to control the display language for the oauth form.

Mastodon.set_language(lang)[source]

Set the locale Mastodon will use to generate responses. Valid parameters are all ISO 639-1 (two letter) or, for languages that do not have one, 639-3 (three letter) language codes. This affects some error messages (those related to validation) and trends.

Mastodon.revoke_access_token()[source]

Revoke the oauth token the user is currently authenticated with, effectively removing the apps access and requiring the user to log in again.

Mastodon.create_account(username: str, password: str, email: str, agreement: bool = False, reason: str | None = None, locale: str = 'en', scopes: List[str] = ['read', 'write', 'follow', 'push'], to_file: str | None = None, return_detailed_error: bool = False) str | None | Tuple[str | None, AccountCreationError][source]

Creates a new user account with the given username, password and email. “agreement” must be set to true (after showing the user the instance’s user agreement and having them agree to it), “locale” specifies the language for the confirmation email as an ISO 639-1 (two letter) or, if a language does not have one, 639-3 (three letter) language code. reason can be used to specify why a user would like to join if approved-registrations mode is on.

Does not require an access token, but does require a client grant.

By default, this method is rate-limited by IP to 5 requests per 30 minutes.

Returns an access token (just like log_in), which it can also persist to to_file, and sets it internally so that the user is now logged in. Note that this token can only be used after the user has confirmed their email.

By default, the function will throw if the account could not be created. Alternately, when return_detailed_error is passed, Mastodon.py will return the detailed error response that the API provides (Starting from version 3.4.0 - not checked here) as an dict with error details as the second return value and the token returned as None in case of error. The dict will contain a text error values as well as a details value which is a dict with one optional key for each potential field (username, password, email and agreement), each if present containing a dict with an error category and free text description. Valid error categories are:

  • ERR_BLOCKED - When e-mail provider is not allowed

  • ERR_UNREACHABLE - When e-mail address does not resolve to any IP via DNS (MX, A, AAAA)

  • ERR_TAKEN - When username or e-mail are already taken

  • ERR_RESERVED - When a username is reserved, e.g. “webmaster” or “admin”

  • ERR_ACCEPTED - When agreement has not been accepted

  • ERR_BLANK - When a required attribute is blank

  • ERR_INVALID - When an attribute is malformed, e.g. wrong characters or invalid e-mail address

  • ERR_TOO_LONG - When an attribute is over the character limit

  • ERR_TOO_SHORT - When an attribute is under the character requirement

  • ERR_INCLUSION - When an attribute is not one of the allowed values, e.g. unsupported locale

Added: Mastodon v2.7.0, last changed: Mastodon v2.7.0

Mastodon.email_resend_confirmation()[source]

Requests a re-send of the users confirmation mail for an unconfirmed logged in user.

Only available to the app that the user originally signed up with.

Added: Mastodon v3.4.0, last changed: Mastodon v3.4.0

User preferences

Mastodon.preferences() Preferences[source]

Fetch the user’s preferences, which can be used to set some default options. As of 2.8.0, apps can only fetch, not update preferences.

Added: Mastodon v2.8.0, last changed: Mastodon v2.8.0