PHP wrapper for the Mastodon API, that includes OAuth helpers. Guzzle based.
This is a plain API wrapper, so it makes it more resilient to changes (new parameters, ...) from the API by letting the developer pass the desired endpoint and parameters.
Install it via Composer.
Latest version requires PHP 8.1. For previous versions of PHP, use v0.1.0
.
composer require colorfield/mastodon-api
Some requests, like public timelines, do not require any authentication.
Initialize the API.
$name = 'MyMastodonApp';
$instance = 'mastodon.social';
$config = new Colorfield\Mastodon\ConfigurationVO($name, $instance);
$this->api = new MastodonAPI($config);
Request a public endpoint.
$timeline = $this->api->getPublicData('/timelines/public');
which is equivalent to
$timeline = $this->api->get('/timelines/public', [], false);
where the 3rd parameter indicates that we don't require any authentication.
This is needed for endpoints that are requiring a token.
To get OAuth credentials, a lightweight client is also available in test_oauth, via a local PHP server. It provides the client id, client secret and bearer. See the Development section below.
$name = 'MyMastodonApp';
$instance = 'mastodon.social';
$oAuth = new Colorfield\Mastodon\MastodonOAuth($name, $instance);
The default configuration is limited to the read
and write
scopes.
You can modify it via
$oAuth->config->setScopes(['read', 'write', 'follow', 'push']);
or alternatively use enum
$oAuth->config->setScopes([
OAuthScope::read->name,
OAuthScope::write->name,
OAuthScope::follow->name,
OAuthScope::push->name
]);
Note that this must be done while obtaining the token, so you cannot override this after. More about scopes.
$authorizationUrl = $oAuth->getAuthorizationUrl();
Store the authorization code in the configuration value object.
$oAuth->config->setAuthorizationCode(xxx);
Then get the access token. As a side effect, it is store in the Configuration value object.
$oAuth->getAccessToken();
The OAuth credentials should be stored in the Configuration value object for later retrieval.
$name = 'MyMastodonApp';
$instance = 'mastodon.social';
$oAuth = new Colorfield\Mastodon\MastodonOAuth($name, $instance);
$oAuth->config->setClientId('...');
$oAuth->config->setClientSecret('...');
$oAuth->config->setBearer('...');
$mastodonAPI = new Colorfield\Mastodon\MastodonAPI($oAuth->config);
Login with Mastodon email and password.
$oAuth->authenticateUser($email, $password);
Get credentials (assumes by default that authentication is provided).
$credentials = $mastodonAPI->get('/accounts/verify_credentials');
Get followers
$followers = $mastodonAPI->get('/accounts/USER_ID/followers');
Clear notifications
$clearedNotifications = $mastodonAPI->post('/notifications/clear');
@todo complete with delete, put, patch and stream.
An interactive demo is available.
composer install
php -S localhost:8000
.env.local
as .env