mastodon_api 0.6.1 mastodon_api: ^0.6.1 copied to clipboard
The easiest and powerful Dart/Flutter library for Mastodon API.
The Easiest and Powerful Dart/Flutter Library for Mastodon API π―
- 1. Guide π
- 1.1. Features π
- 1.2. Getting Started β‘
- 1.3. Supported Endpoints π
- 1.4. Tips π
- 1.5. Contribution π
- 1.6. Contributors β¨
- 1.7. Support β€οΈ
- 1.8. License π
- 1.9. More Information π§
1. Guide π #
This library provides the easiest way to use Mastodon API in Dart and Flutter apps.
This library was designed and developed by Kato Shinya (@myConsciousness), the author of twitter_api_v2, and many parts are adapted from twitter_api_v2.
Show some β€οΈ and star the repo to support the project.
We also provide mastodon_oauth2 for easy OAuth 2.0 when using the Mastodon API!
1.1. Features π #
β
The wrapper library for Mastodon API.
β
Easily integrates with the Dart & Flutter apps.
β
Provides response objects with a guaranteed safe types.
β
Well documented and well tested.
β
Supports the powerful automatic retry.
1.2. Getting Started β‘ #
1.2.1. Install Library #
With Dart:
dart pub add mastodon_api
Or With Flutter:
flutter pub add mastodon_api
1.2.2. Import #
import 'package:mastodon_api/mastodon_api';
1.2.3. Implementation #
import 'package:mastodon_api/mastodon_api.dart';
Future<void> main() async {
//! You need to specify mastodon instance (domain) you want to access.
//! Also you need to get bearer token from your developer page, or OAuth 2.0.
final mastodon = MastodonApi(
instance: 'MASTODON_INSTANCE',
bearerToken: 'YOUR_BEARER_TOKEN',
//! Automatic retry is available when server error or network error occurs
//! when communicating with the API.
retryConfig: RetryConfig(
maxAttempts: 5,
jitter: Jitter(
minInSeconds: 2,
maxInSeconds: 5,
),
onExecute: (event) => print(
'Retry after ${event.intervalInSeconds} seconds... '
'[${event.retryCount} times]',
),
),
//! The default timeout is 10 seconds.
timeout: Duration(seconds: 20),
);
try {
//! Let's Toot from v1 endpoint!
final response = await mastodon.v1.statuses.createStatus(
text: 'Toot!',
);
print(response.rateLimit);
print(response.data);
} on UnauthorizedException catch (e) {
print(e);
} on RateLimitExceededException catch (e) {
print(e);
} on MastodonException catch (e) {
print(e.response);
print(e.body);
print(e);
}
}
1.3. Supported Endpoints π #
1.3.1. Instance Service #
1.3.1.1. v1
1.3.1.2. v2
Endpoint | Method Name |
---|---|
GET /api/v2/instance | lookupInformation |
1.3.2. Apps Service #
1.3.2.1. v1
Endpoint | Method Name |
---|---|
POST /api/v1/apps | createApplication |
GET /api/v1/apps/verify_credentials | verifyOAuthCredentials |
POST /api/v1/emails/confirmation | createNewConfirmationEmail |
1.3.2.2. v2
1.3.3. Search Service #
1.3.3.1. v1
1.3.3.2. v2
Endpoint | Method Name |
---|---|
GET /api/v2/search | searchContents |
1.3.4. Accounts Service #
1.3.4.1. v1
1.3.4.2. v2
Endpoint | Method Name |
---|---|
GET /api/v2/suggestions | lookupFollowSuggestions |
1.3.5. Timelines Service #
1.3.5.1. v1
1.3.6. Statuses Service #
1.3.6.1. v1
1.3.6.2. v2
1.3.7. Notifications Service #
1.3.7.1. v1
1.3.7.2. v2
1.3.8. OEmbed Service #
1.3.8.1. v1
Endpoint | Method Name |
---|---|
GET /api/oembed | lookupOEmbedMetadata |
1.3.8.2. v2
1.3.9. Media Service #
1.3.9.1. v1
Endpoint | Method Name |
---|---|
POST /api/v1/media (deprecated) | uploadMedia |
GET /api/v1/media/:id | lookupMedia |
PUT /api/v1/media/:id | updateMedia |
1.3.9.2. v2
Endpoint | Method Name |
---|---|
POST /api/v2/media | uploadMedia |
1.4. Tips π #
1.4.1. Method Names #
mastodon_api uses the following standard prefixes depending on endpoint characteristics. So it's very easy to find the method corresponding to the endpoint you want to use!
Prefix | Description |
---|---|
lookup | This prefix is attached to endpoints that reference toots, accounts, etc. |
search | This prefix is attached to endpoints that perform extensive searches. |
connect | This prefix is attached to endpoints with high-performance streaming. |
create | This prefix is attached to the endpoint performing the create state such as Toot and Follow . |
destroy | This prefix is attached to the endpoint performing the destroy state such as Toot and Follow . |
update | This prefix is attached to the endpoint performing the update state. |
upload | This prefix is attached to the endpoint performing the media uploading. |
verify | This prefix is attached to the endpoint performing the verify specific states or values. |
1.4.2. Null Parameter at Request #
In this library, parameters that are not required at request time, i.e., optional parameters, are defined as nullable. However, developers do not need to be aware of the null parameter when sending requests when using this library.
It means the parameters specified with a null value are safely removed and ignored before the request is sent.
For example, arguments specified with null are ignored in the following request.
import 'package:mastodon_api/mastodon_api.dart';
Future<void> main() async {
final mastodon = MastodonApi(
instance: 'MASTODON_INSTANCE',
bearerToken: 'YOUR_BEARER_TOKEN',
);
await mastodon.v1.statuses.createStatus(
text: 'Toot!',
//! These parameters are ignored at request because they are null.
poll: null,
sensitive: null,
);
}
1.4.3. OAuth 2.0 Authorization Code Flow #
Mastodon API supports authentication methods with OAuth 2.0, and it allows users of apps using Mastodon API to request authorization for the minimum necessary scope of operation.
Since OAuth2.0 authentication requires going through a browser, mastodon_api does not provide this specification for compatibility with CLI applications. Instead, we provide mastodon_oauth2, a library for Flutter apps.
The mastodon_oauth2 is 100% compatible with mastodon_api and can be used. You can see more details from links below.
1.4.4. Change the Timeout Duration #
The library specifies a default timeout of 10 seconds for all API communications.
However, there may be times when you wish to specify an arbitrary timeout duration. If there is such a demand, an arbitrary timeout duration can be specified as follows.
import 'package:mastodon_api/mastodon_api.dart';
Future<void> main() {
final mastodon = MastodonApi(
instance: 'MASTODON_INSTANCE',
bearerToken: 'YOUR_TOKEN_HERE',
//! The default timeout is 10 seconds.
timeout: Duration(seconds: 20),
);
}
1.4.5. Automatic Retry #
Due to the nature of this library's communication with external systems, timeouts may occur due to inevitable communication failures or temporary crashes of the server to which requests are sent.
When such timeouts occur, an effective countermeasure in many cases is to send the request again after a certain interval. And mastodon_api provides an automatic retry feature as a solution to this problem.
Also, errors subject to retry are as follows.
- When the status code of the response returned from Mastodon is
500
or503
. - When the network is temporarily lost and a
SocketException
is thrown. - When communication times out temporarily and a
TimeoutException
is thrown
1.4.5.1. Exponential Backoff and Jitter
Although the algorithm introduced earlier that exponentially increases the retry interval is already powerful, some may believe that it is not yet sufficient to distribute the sensation of retries. It's more distributed than equally spaced retries, but retries still occur at static intervals.
This problem can be solved by adding a random number called Jitter, and this method is called the Exponential Backoff and Jitter algorithm. By adding a random number to the exponentially increasing retry interval, the retry interval can be distributed more flexibly.
Similar to the previous example, mastodon_api can be implemented as follows.
import 'package:mastodon_api/mastodon_api.dart';
Future<void> main() async {
final mastodon = MastodonApi(
instance: 'MASTODON_INSTANCE',
bearerToken: 'YOUR_TOKEN_HERE',
//! Add these lines.
retryConfig: RetryConfig(
maxAttempts: 3,
),
);
}
In the above implementation, the interval increases exponentially for each retry count with jitter. It can be expressed by next formula.
(2 ^ retryCount) + jitter(Random Number between 0 ~ 3)
1.4.5.2. Do Something on Retry
It would be useful to output logging on retries and a popup notifying the user that a retry has been executed. So mastodon_api provides callbacks that can perform arbitrary processing when retries are executed.
It can be implemented as follows.
import 'package:mastodon_api/mastodon_api.dart';
Future<void> main() async {
final mastodon = MastodonApi(
instance: 'MASTODON_INSTANCE',
bearerToken: 'YOUR_TOKEN_HERE',
retryConfig: RetryConfig(
maxAttempts: 3,
//! Add this line.
onExecute: (event) => print('Retrying... ${event.retryCount} times.'),
),
);
}
The RetryEvent passed to the callback contains information on retries.
1.4.6. Thrown Exceptions #
mastodon_api provides a convenient exception object for easy handling of exceptional responses and errors returned from Mastodon API.
Exception | Description |
---|---|
MastodonException | The most basic exception object. For example, it can be used to search for posts that have already been deleted, etc. |
UnauthorizedException | Thrown when authentication fails with the specified access token. |
RateLimitExceededException | Thrown when the request rate limit is exceeded. |
DataNotFoundException | Thrown when response has no body or data field in body string, or when 404 status is returned. |
Also, all of the above exceptions thrown from the mastodon_api process extend MastodonException. This means that you can take all exceptions as MastodonException or handle them as certain exception types, depending on the situation.
However note that, if you receive an individual type exception, be sure to define the process so that the individual exception type is cached before MastodonException. Otherwise, certain type exceptions will also be caught as MastodonException.
Therefore, if you need to catch a specific type of exception in addition to MastodonException, be sure to catch MastodonException in the bottom catch clause as in the following example.
import 'package:mastodon_api/mastodon_api.dart';
Future<void> main() async {
final mastodon = MastodonApi(
instance: 'MASTODON_INSTANCE',
bearerToken: 'YOUR_TOKEN_HERE',
);
try {
final response = await mastodon.v1.statuses.createStatus(text: 'Toot!');
print(response);
} on UnauthorizedException catch (e) {
print(e);
} on RateLimitExceededException catch (e) {
print(e);
} on MastodonException catch (e) {
print(e);
}
}
1.5. Contribution π #
If you would like to contribute to mastodon_api, please create an issue or create a Pull Request.
There are many ways to contribute to the OSS. For example, the following subjects can be considered:
- There are request parameters or response fields that are not implemented.
- Documentation is outdated or incomplete.
- Have a better way or idea to achieve the functionality.
- etc...
You can see more details from resources below:
Or you can create a discussion if you like.
Feel free to join this development, diverse opinions make software better!
1.6. Contributors β¨ #
Thanks goes to these wonderful people (emoji key):
This project follows the all-contributors specification. Contributions of any kind welcome!
1.7. Support β€οΈ #
The simplest way to show us your support is by giving the project a star at GitHub and Pub.dev.
You can also support this project by becoming a sponsor on GitHub:
You can also show on your repository that your app is made with mastodon_api by using one of the following badges:
[![Powered by mastodon_api](https://img.shields.io/badge/Powered%20by-mastodon_api-00acee.svg)](https://github.com/mastodon-dart/mastodon-api)
[![Powered by mastodon_api](https://img.shields.io/badge/Powered%20by-mastodon_api-00acee.svg?style=flat-square)](https://github.com/mastodon-dart/mastodon-api)
[![Powered by mastodon_api](https://img.shields.io/badge/Powered%20by-mastodon_api-00acee.svg?style=for-the-badge)](https://github.com/mastodon-dart/mastodon-api)
1.8. License π #
All resources of mastodon_api is provided under the BSD-3
license.
Copyright 2022 Kato Shinya. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided the conditions.
Note
License notices in the source are strictly validated based on.github/header-checker-lint.yml
. Please check header-checker-lint.yml for the permitted standards.
1.9. More Information π§ #
mastodon_api was designed and implemented by Kato Shinya (@myConsciousness).