Python wrapper for the Mastodon API

2.2.1 · active · verified Thu Apr 16

Mastodon.py is an actively maintained Python wrapper for the Mastodon API, providing a feature-complete client for interacting with Mastodon instances. It is currently at version 2.2.1 and receives regular updates to support new Mastodon API features and fix bugs.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to authenticate with a Mastodon instance using an access token and post a status (toot). It assumes you have already registered an application and obtained a user access token. For production, store your `MASTODON_ACCESS_TOKEN` and `MASTODON_API_BASE_URL` as environment variables. The commented-out sections show the `create_app` and `log_in` steps for initial setup.

import os
from mastodon import Mastodon

# --- App Registration (Run once per server/app) ---
# client_id, client_secret = Mastodon.create_app(
#     'MyPythonApp',
#     api_base_url = 'https://mastodon.social',
#     to_file = 'pytooter_clientcred.secret'
# )

# --- User Login (Run once per user/app) ---
# mastodon = Mastodon(client_id = 'pytooter_clientcred.secret')
# # print(mastodon.auth_request_url())
# # code = input("Enter the OAuth authorization code: ")
# # mastodon.log_in(code=code, to_file="pytooter_usercred.secret")

# --- Usage with existing credentials ---
# It's recommended to store sensitive tokens securely (e.g., environment variables).
# For quick testing, you can load from file if previously saved.
# ACCESS_TOKEN_FILE = 'pytooter_usercred.secret'
# if os.path.exists(ACCESS_TOKEN_FILE):
#     api_base_url = None # Will be loaded from file if present
#     with open(ACCESS_TOKEN_FILE, 'r') as f:
#         # Simple parsing for demo, real-world might use better config handling
#         lines = f.readlines()
#         for line in lines:
#             if 'api_base_url' in line:
#                 api_base_url = line.split('=')[1].strip()
#                 break
#     mastodon = Mastodon(access_token=ACCESS_TOKEN_FILE, api_base_url=api_base_url)
# else:
MASTODON_ACCESS_TOKEN = os.environ.get('MASTODON_ACCESS_TOKEN', '')
MASTODON_API_BASE_URL = os.environ.get('MASTODON_API_BASE_URL', 'https://mastodon.social')

if not MASTODON_ACCESS_TOKEN:
    print("Error: MASTODON_ACCESS_TOKEN environment variable not set. Please set it or uncomment app registration/login code.")
    exit(1)

print(f"Connecting to Mastodon instance: {MASTODON_API_BASE_URL}")
mastodon = Mastodon(
    access_token=MASTODON_ACCESS_TOKEN,
    api_base_url=MASTODON_API_BASE_URL
)

try:
    # Get current authenticated user's account details
    me = mastodon.account_verify_credentials()
    print(f"Successfully authenticated as @{me.acct}")

    # Post a status (toot)
    status = mastodon.status_post('Hello from mastodon-py! #python #mastodonpy')
    print(f"Tooted: {status.url}")

except Exception as e:
    print(f"An error occurred: {e}")

view raw JSON →