PHPackages                             vazaha-nl/mastodon-api-client - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. vazaha-nl/mastodon-api-client

ActiveLibrary[API Development](/categories/api)

vazaha-nl/mastodon-api-client
=============================

A fully typed and feature complete Mastodon API client for PHP

v2.0.0(8mo ago)251.5k↑133.3%3[1 PRs](https://github.com/vazaha-nl/mastodon-api-client/pulls)1MITPHPPHP &gt;=8.1CI passing

Since Aug 2Pushed 8mo ago3 watchersCompare

[ Source](https://github.com/vazaha-nl/mastodon-api-client)[ Packagist](https://packagist.org/packages/vazaha-nl/mastodon-api-client)[ RSS](/packages/vazaha-nl-mastodon-api-client/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (8)Dependencies (14)Versions (10)Used By (1)

mastodon-api-client
===================

[](#mastodon-api-client)

A fully typed and complete [mastodon API](https://docs.joinmastodon.org/api/) client for PHP.

Features
--------

[](#features)

- complete: every documented api method and entity has been implemented
- fully typed: every function, argument, property and result is typed, using generics where applicable
- documented: every api entity, method and argument is documented using docblocks, and contain a link to the relevant page at
- tested: the code is covered by unit and integration tests, and passes phpstan analysis on the highest level
- up to date: classes are auto generated based on the [Mastodon markup documentation](https://github.com/mastodon/documentation) (in absence of a good openapi spec)

Requirements
------------

[](#requirements)

- PHP &gt;= 8.1

Installation
------------

[](#installation)

```
composer require vazaha-nl/mastodon-api-client

```

Usage
-----

[](#usage)

### Create the api client

[](#create-the-api-client)

```
// using the factory
$factory = new \Vazaha\Mastodon\Factories\ApiClientFactory();
$client = $factory->build();

// instantiate directly, with the httpclient implementation of your choice
$client = new \Vazaha\Mastodon\ApiClient(new \GuzzleHttp\Client());
```

### Set base uri / token

[](#set-base-uri--token)

```
// set base uri (required)
$client->setBaseUri('https://instance.example');

// manually set access token
$client->setAccessToken('token...');
```

### Calling API methods

[](#calling-api-methods)

Every method is exposed through the `$client->methods()` proxy. It is highly recommended to use a [LSP enabled IDE](https://langserver.org/).

The methods are named and organized exactly like in the [official documentation](https://docs.joinmastodon.org/methods/), with documentation in docblocks.

#### Calls with a single result

[](#calls-with-a-single-result)

All API calls that return a single entity, will return a subclass of `\Vazaha\Mastodon\Models\Model`.

```
try {
    // get an account by id
    // returns instance of \Vazaha\Mastodon\Models\AccountModel
    $account = $client->methods()->accounts()->get('the account id');
} catch (NotFoundException $e) {
    // no account exists with this id
    $error = $e->getError(); // instance of \Vazaha\Mastodon\Models\ErrorModel
    // ..
}

print 'Found account: ' . $account->display_name . \PHP_EOL;
```

#### Calls with multiple results

[](#calls-with-multiple-results)

Calls that return a list of entities, will return a subclass of `\Vazaha\Mastodon\Results\Result`. This class is a subclass of `\Illuminate\Support\Collection` which can be accessed as an array. The collection will contain the result model(s) (implementations of `\Vazaha\Interfaces\ModelInterface`). The exact subclass will be type hinted and thus known to your IDE.

```
// get the followers of account with specified id.
// returns instance of \Vazaha\Mastodon\Results\AccountResult
$followers = $client->methods()->accounts()->followers($account->id);

foreach ($followers as $follower) {
    // contains \Vazaha\Mastodon\Models\AccountModel instances
    print 'Follower : ' . $follower->display_name . \PHP_EOL;
}
```

#### Pagination

[](#pagination)

Most API calls with multiple results have a hard limit on the amount of results returned. To get the next/previous page of a result, use the `getNextPage()` / `getPreviousPage()` methods. This is done by parsing the `Link` http header. See for background:

```
while ($followers = $followers->getNextPage()) {
    // ...
}
```

#### Calls with empty or custom result

[](#calls-with-empty-or-custom-result)

Some calls do not return a model or array of models. Some have an empty result, some have a custom result, like an array of strings or custom hashes, or plain text. Refer to the documentation for details. In all those cases the Result will be an instance of `\Vazaha\Mastodon\Results\EmptyOrUnknownResult`, and the collection will be empty. Retrieve the response using one of the following methods:

```
// get the decoded json content, if available
$decoded = $result->getDecodedBody();

// get the undecoded response body
$body = $result->getBody();

// get the entire Http Response object
$response = $result->getHttpResponse();
```

#### Error handling

[](#error-handling)

In case of any client (4xx) http errors, custom exceptions (subclasses of `\Vazaha\Mastodon\Exceptions\ApiErrorException`) will be thrown, containing an [Error](https://docs.joinmastodon.org/entities/Error/) object. There is a specific exception class for every status code.

#### More usage examples

[](#more-usage-examples)

See the `examples/` folder.

### Laravel support

[](#laravel-support)

The `ServiceProvider` class, which will be automatically detected, provides very basic Laravel support, enabling dependency injection of the ApiClient class. For example in a controller:

```
public function myControllerFunction(Request $request, ApiClient $client)
{
    /** @var \App\Models\User $user */
    $user = $request->user();
    $client->setBaseUri('https://instance.example')
        ->setAccessToken($user->mastodon_access_token);
    // ...
}
```

Testing
-------

[](#testing)

### Phpstan

[](#phpstan)

All code should pass phpstan analysis on level 9.

```

composer analyse

```

### Unit tests

[](#unit-tests)

```

composer test

```

### Integration tests

[](#integration-tests)

These tests run on an actual (local!) mastodon instance. Do not use a live server for this.

The easiest way to set up a local mastodon server is using Vagrant. See  for instructions. It is assumed that this server runs at . If you have a different setup, set the domain in `tests/Integration/.env`:

```

BASE_URI=http://your-local-mastodon-domain.tld

```

To run the tests, you will need a valid access token for the admin user. To get one, run the `tests/Integration/get_admin_access_token.php` script and follow the prompts. It will create an app and take you through the oauth flow. The credentials will be stored in `tests/Integration/.env`.

Apart from the admin token, you will also need a local test mastodon user `user1`. You can create one using the `toot` util. If you're using vagrant:

```
cd

# bring the server up, if needed:
vagrant up

# ssh into your vagrant machine
vagrant ssh

cd /vagrant

# create a confirmed user
bin/tootctl accounts create user1 --email=user1@example.com --confirmed

# approve the user
bin/tootctl accounts modify user1 --approve

```

Running the integration tests:

```

composer integration-test

```

Coding style
------------

[](#coding-style)

Coding style is enforced using `php-cs-fixer`.

```

# check only, no modifications will be made
composer check-style

# fix all files if possible
composer fix-style

```

Bugs, issues, questions, comments?
----------------------------------

[](#bugs-issues-questions-comments)

Please open an issue on GitHub, send me a mail, or get in touch on Mastodon: .

Author
------

[](#author)

Lennart Hengstmengel

License
-------

[](#license)

This software is open sourced software licensed under the [MIT license](https://opensource.org/licenses/MIT).

###  Health Score

44

—

FairBetter than 92% of packages

Maintenance59

Moderate activity, may be stable

Popularity31

Limited adoption so far

Community15

Small or concentrated contributor base

Maturity58

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 99.5% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~108 days

Recently: every ~187 days

Total

8

Last Release

261d ago

Major Versions

v0.4.0-rc2 → v1.0.02023-08-11

v1.1.0 → v2.0.02025-08-30

### Community

Maintainers

![](https://www.gravatar.com/avatar/30c767360f5c6bca984c9c87e7cfaac0e383ca254e8c910dacb4fc5f80284aec?d=identicon)[vazaha-nl](/maintainers/vazaha-nl)

---

Top Contributors

[![vazaha-nl](https://avatars.githubusercontent.com/u/1075085?v=4)](https://github.com/vazaha-nl "vazaha-nl (205 commits)")[![4thguy](https://avatars.githubusercontent.com/u/1839897?v=4)](https://github.com/4thguy "4thguy (1 commits)")

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/vazaha-nl-mastodon-api-client/health.svg)

```
[![Health](https://phpackages.com/badges/vazaha-nl-mastodon-api-client/health.svg)](https://phpackages.com/packages/vazaha-nl-mastodon-api-client)
```

###  Alternatives

[vluzrmos/slack-api

Wrapper for Slack.com WEB API.

102589.1k3](/packages/vluzrmos-slack-api)[ashallendesign/laravel-exchange-rates

A wrapper package for interacting with the exchangeratesapi.io API.

485677.8k](/packages/ashallendesign-laravel-exchange-rates)[smodav/mpesa

M-Pesa API implementation

16363.7k1](/packages/smodav-mpesa)[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

245.2k](/packages/aedart-athenaeum)[specialtactics/l5-api

Dependencies for the Laravel API Boilerplate package

3672.8k2](/packages/specialtactics-l5-api)[grantholle/powerschool-api

A Laravel package to make interacting with PowerSchool less painful.

1715.6k1](/packages/grantholle-powerschool-api)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
