mastodon_api 0.6.1

SDKdartflutter
Platformandroidioswindowslinuxmacos

The easiest and powerful Dart/Flutter library for Mastodon API.

mastodon_api

The Easiest and Powerful Dart/Flutter Library for Mastodon API 🎯


GitHub Sponsor GitHub Sponsor

pub package Dart SDK Version Test Analyzer codecov Issues Pull Requests Stars Contributors Code size Last Commits License Contributor Covenant


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

EndpointMethod Name
GET /api/v1/instance (deprecated)lookupInformation
GET /api/v1/instance/peerslookupConnectedDomains
GET /api/v1/instance/activitylookupWeeklyActivities
GET /api/v1/instance/ruleslookupRules
GET /api/v1/instance/domain_blocklookupBlockedDomains
GET /api/v1/examplelookupExtendedDescription
GET /api/v1/announcementslookupAnnouncements
lookupActiveAnnouncements
POST /api/v1/announcements/:id/dismisscreateMarkAnnouncementAsRead
PUT /api/v1/announcements/:id/reactions/:namecreateReactionToAnnouncement
DELETE /api/v1/announcements/:id/reactions/:namedestroyReactionToAnnouncement
GET /api/v1/custom_emojislookupAvailableEmoji
GET /api/v1/directorylookupAccounts

1.3.1.2. v2

EndpointMethod Name
GET /api/v2/instancelookupInformation

1.3.2. Apps Service

1.3.2.1. v1

EndpointMethod Name
POST /api/v1/appscreateApplication
GET /api/v1/apps/verify_credentialsverifyOAuthCredentials
POST /api/v1/emails/confirmationcreateNewConfirmationEmail

1.3.2.2. v2

1.3.3. Search Service

1.3.3.1. v1

1.3.3.2. v2

EndpointMethod Name
GET /api/v2/searchsearchContents

1.3.4. Accounts Service

1.3.4.1. v1

EndpointMethod Name
POST /api/v1/accountscreateAccount
GET /api/v1/accounts/verify_credentialsverifyAccountCredentials
PATCH /api/v1/accounts/update_credentialsupdateAccount
PATCH /api/v1/accounts/update_credentialsupdateAvatarImage
PATCH /api/v1/accounts/update_credentialsupdateHeaderImage
GET /api/v1/accounts/:idlookupAccount
GET /api/v1/accounts/:id/statuseslookupStatuses
GET /api/v1/accounts/:id/followerslookupFollowers
GET /api/v1/accounts/:id/followinglookupFollowings
GET /api/v1/accounts/:id/featured_tagslookupFeaturedTags
GET /api/v1/accounts/:id/listslookupContainedLists
POST /api/v1/accounts/:id/followcreateFollow
POST /api/v1/accounts/:id/unfollowdestroyFollow
POST /api/v1/accounts/:id/remove_from_followersdestroyFollower
POST /api/v1/accounts/:id/blockcreateBlock
POST /api/v1/accounts/:id/unblockdestroyBlock
POST /api/v1/accounts/:id/mutecreateMute
POST /api/v1/accounts/:id/unmutedestroyMute
POST /api/v1/accounts/:id/pincreateFeaturedProfile
POST /api/v1/accounts/:id/unpindestroyFeaturedProfile
POST /api/v1/accounts/:id/noteupdatePrivateComment
GET /api/v1/accounts/relationshipslookupRelationships
GET /api/v1/accounts/familiar_followerslookupFamiliarFollowers
GET /api/v1/accounts/searchsearchAccounts
GET /api/v1/accounts/lookuplookupAccountFromWebFingerAddress
GET /api/v1/preferenceslookupPreferences
GET /api/v1/featured_tagslookupOwnedFeaturedTags
POST /api/v1/featured_tagscreateFeaturedTag
DELETE /api/v1/featured_tags/:iddestroyFeaturedTag
GET /api/v1/featured_tags/suggestionslookupSuggestedTags
GET /api/v1/followed_tagslookupFollowedTags
DELETE /api/v1/suggestions/:account_iddestroyFollowSuggestion
GET /api/v1/tags/:idlookupTag
POST /api/v1/tags/:id/followcreateFollowingTag
POST /api/v1/tags/:id/unfollowdestroyFollowingTag
POST /api/v1/reportscreateReport
GET /api/v1/endorsementslookupFeaturedProfiles
GET /api/v1/muteslookupMutedAccounts
GET /api/v1/favouriteslookupFavouritedStatuses
GET /api/v1/blockslookupBlockedAccounts
GET /api/v1/bookmarkslookupBookmarkedStatuses
GET /api/v1/domain_blockslookupBlockedDomains
POST /api/v1/domain_blockscreateBlockedDomain
DELETE /api/v1/domain_blocksdestroyBlockedDomain
GET /api/v1/follow_requestslookupFollowRequests
POST /api/v1/follow_requests/:account_id/authorizecreateFollower
POST /api/v1/follow_requests/:account_id/rejectdestroyFollowRequest

1.3.4.2. v2

EndpointMethod Name
GET /api/v2/suggestionslookupFollowSuggestions

1.3.5. Timelines Service

1.3.5.1. v1

EndpointMethod Name
GET /api/v1/timelines/publiclookupPublicTimeline
GET /api/v1/timelines/tag/:hashtaglookupTimelineByHashtag
GET /api/v1/timelines/homelookupHomeTimeline
GET /api/v1/timelines/list/:list_idlookupListTimeline
GET /api/v1/conversationslookupConversations
DELETE /api/v1/conversations/:iddestroyConversation
POST /api/v1/conversations/:id/readcreateMarkConversationAsRead
GET /api/v1/markerslookupStatusSnapshot
GET /api/v1/markerslookupNotificationSnapshot
POST /api/v1/markerscreateStatusSnapshot
POST /api/v1/markerscreateNotificationSnapshot

1.3.6. Statuses Service

1.3.6.1. v1

EndpointMethod Name
POST /api/v1/statusescreateStatus
GET /api/v1/polls/:idlookupPollById
POST /api/v1/polls/:id/votescreateVote
createVotes
GET /api/v1/statuses/:idlookupStatus
DELETE /api/v1/statuses/:iddestroyStatus
GET /api/v1/statuses/:id/contextlookupStatusContext
GET /api/v1/statuses/:id/reblogged_bylookupRebloggedUsers
GET /api/v1/statuses/:id/favourited_bylookupFavouritedUsers
POST /api/v1/statuses/:id/favouritecreateFavourite
POST /api/v1/statuses/:id/unfavouritedestroyFavourite
POST /api/v1/statuses/:id/reblogcreateReblog
POST /api/v1/statuses/:id/unreblogdestroyReblog
POST /api/v1/statuses/:id/bookmarkcreateBookmark
POST /api/v1/statuses/:id/unbookmarkdestroyBookmark
POST /api/v1/statuses/:id/mutecreateMute
POST /api/v1/statuses/:id/unmutedestroyMute
POST /api/v1/statuses/:id/pincreatePinnedStatus
POST /api/v1/statuses/:id/unpindestroyPinnedStatus
PUT /api/v1/statuses/:idupdateStatus
GET /api/v1/statuses/:id/historylookupEditHistory
GET /api/v1/statuses/:id/sourcelookupEditableSource
GET /api/v1/scheduled_statuseslookupScheduledStatuses
GET /api/v1/scheduled_statuses/:idlookupScheduledStatus
PUT /api/v1/scheduled_statuses/:idupdateScheduledStatus
DELETE /api/v1/scheduled_statuses/:iddestroyScheduledStatus

1.3.6.2. v2

1.3.7. Notifications Service

1.3.7.1. v1

EndpointMethod Name
GET /api/v1/notificationslookupNotifications
GET /api/v1/notification/:idlookupNotification
POST /api/v1/notifications/cleardestroyAllNotifications
POST /api/v1/notifications/:id/dismissdestroyNotification

1.3.7.2. v2

1.3.8. OEmbed Service

1.3.8.1. v1

EndpointMethod Name
GET /api/oembedlookupOEmbedMetadata

1.3.8.2. v2

1.3.9. Media Service

1.3.9.1. v1

EndpointMethod Name
POST /api/v1/media (deprecated)uploadMedia
GET /api/v1/media/:idlookupMedia
PUT /api/v1/media/:idupdateMedia

1.3.9.2. v2

EndpointMethod Name
POST /api/v2/mediauploadMedia

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!

PrefixDescription
lookupThis prefix is attached to endpoints that reference toots, accounts, etc.
searchThis prefix is attached to endpoints that perform extensive searches.
connectThis prefix is attached to endpoints with high-performance streaming.
createThis prefix is attached to the endpoint performing the create state such as Toot and Follow.
destroyThis prefix is attached to the endpoint performing the destroy state such as Toot and Follow.
updateThis prefix is attached to the endpoint performing the update state.
uploadThis prefix is attached to the endpoint performing the media uploading.
verifyThis 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 or 503.
  • 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.

ExceptionDescription
MastodonExceptionThe most basic exception object. For example, it can be used to search for posts that have already been deleted, etc.
UnauthorizedExceptionThrown when authentication fails with the specified access token.
RateLimitExceededExceptionThrown when the request rate limit is exceeded.
DataNotFoundExceptionThrown 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):

KATO, Shinya / 加藤 真也
KATO, Shinya / 加藤 真也

💻 📖 🎨 💡 🔍 🤔 🚧 🛡️ ⚠️ ✅
Mark O'Sullivan
Mark O'Sullivan

📖 🤔 💬
Mike Sheldon
Mike Sheldon

🤔 🖋 💻 🐛 ⚠️
YeongJun
YeongJun

🤔 💻
alevinetx
alevinetx

💻 💬 🐛
Igor
Igor

💻 ⚠️ 📖 🐛

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 Powered by mastodon_api Powered by mastodon_api

[![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).