mastodon_api 0.6.1 copy "mastodon_api: ^0.6.1" to clipboard
mastodon_api: ^0.6.1 copied to clipboard

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

Endpoint Method Name
GET /api/v1/instance (deprecated) lookupInformation
GET /api/v1/instance/peers lookupConnectedDomains
GET /api/v1/instance/activity lookupWeeklyActivities
GET /api/v1/instance/rules lookupRules
GET /api/v1/instance/domain_block lookupBlockedDomains
GET /api/v1/example lookupExtendedDescription
GET /api/v1/announcements lookupAnnouncements
lookupActiveAnnouncements
POST /api/v1/announcements/:id/dismiss createMarkAnnouncementAsRead
PUT /api/v1/announcements/:id/reactions/:name createReactionToAnnouncement
DELETE /api/v1/announcements/:id/reactions/:name destroyReactionToAnnouncement
GET /api/v1/custom_emojis lookupAvailableEmoji
GET /api/v1/directory lookupAccounts

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

Endpoint Method Name
POST /api/v1/accounts createAccount
GET /api/v1/accounts/verify_credentials verifyAccountCredentials
PATCH /api/v1/accounts/update_credentials updateAccount
PATCH /api/v1/accounts/update_credentials updateAvatarImage
PATCH /api/v1/accounts/update_credentials updateHeaderImage
GET /api/v1/accounts/:id lookupAccount
GET /api/v1/accounts/:id/statuses lookupStatuses
GET /api/v1/accounts/:id/followers lookupFollowers
GET /api/v1/accounts/:id/following lookupFollowings
GET /api/v1/accounts/:id/featured_tags lookupFeaturedTags
GET /api/v1/accounts/:id/lists lookupContainedLists
POST /api/v1/accounts/:id/follow createFollow
POST /api/v1/accounts/:id/unfollow destroyFollow
POST /api/v1/accounts/:id/remove_from_followers destroyFollower
POST /api/v1/accounts/:id/block createBlock
POST /api/v1/accounts/:id/unblock destroyBlock
POST /api/v1/accounts/:id/mute createMute
POST /api/v1/accounts/:id/unmute destroyMute
POST /api/v1/accounts/:id/pin createFeaturedProfile
POST /api/v1/accounts/:id/unpin destroyFeaturedProfile
POST /api/v1/accounts/:id/note updatePrivateComment
GET /api/v1/accounts/relationships lookupRelationships
GET /api/v1/accounts/familiar_followers lookupFamiliarFollowers
GET /api/v1/accounts/search searchAccounts
GET /api/v1/accounts/lookup lookupAccountFromWebFingerAddress
GET /api/v1/preferences lookupPreferences
GET /api/v1/featured_tags lookupOwnedFeaturedTags
POST /api/v1/featured_tags createFeaturedTag
DELETE /api/v1/featured_tags/:id destroyFeaturedTag
GET /api/v1/featured_tags/suggestions lookupSuggestedTags
GET /api/v1/followed_tags lookupFollowedTags
DELETE /api/v1/suggestions/:account_id destroyFollowSuggestion
GET /api/v1/tags/:id lookupTag
POST /api/v1/tags/:id/follow createFollowingTag
POST /api/v1/tags/:id/unfollow destroyFollowingTag
POST /api/v1/reports createReport
GET /api/v1/endorsements lookupFeaturedProfiles
GET /api/v1/mutes lookupMutedAccounts
GET /api/v1/favourites lookupFavouritedStatuses
GET /api/v1/blocks lookupBlockedAccounts
GET /api/v1/bookmarks lookupBookmarkedStatuses
GET /api/v1/domain_blocks lookupBlockedDomains
POST /api/v1/domain_blocks createBlockedDomain
DELETE /api/v1/domain_blocks destroyBlockedDomain
GET /api/v1/follow_requests lookupFollowRequests
POST /api/v1/follow_requests/:account_id/authorize createFollower
POST /api/v1/follow_requests/:account_id/reject destroyFollowRequest

1.3.4.2. v2

Endpoint Method Name
GET /api/v2/suggestions lookupFollowSuggestions

1.3.5. Timelines Service #

1.3.5.1. v1

Endpoint Method Name
GET /api/v1/timelines/public lookupPublicTimeline
GET /api/v1/timelines/tag/:hashtag lookupTimelineByHashtag
GET /api/v1/timelines/home lookupHomeTimeline
GET /api/v1/timelines/list/:list_id lookupListTimeline
GET /api/v1/conversations lookupConversations
DELETE /api/v1/conversations/:id destroyConversation
POST /api/v1/conversations/:id/read createMarkConversationAsRead
GET /api/v1/markers lookupStatusSnapshot
GET /api/v1/markers lookupNotificationSnapshot
POST /api/v1/markers createStatusSnapshot
POST /api/v1/markers createNotificationSnapshot

1.3.6. Statuses Service #

1.3.6.1. v1

Endpoint Method Name
POST /api/v1/statuses createStatus
GET /api/v1/polls/:id lookupPollById
POST /api/v1/polls/:id/votes createVote
createVotes
GET /api/v1/statuses/:id lookupStatus
DELETE /api/v1/statuses/:id destroyStatus
GET /api/v1/statuses/:id/context lookupStatusContext
GET /api/v1/statuses/:id/reblogged_by lookupRebloggedUsers
GET /api/v1/statuses/:id/favourited_by lookupFavouritedUsers
POST /api/v1/statuses/:id/favourite createFavourite
POST /api/v1/statuses/:id/unfavourite destroyFavourite
POST /api/v1/statuses/:id/reblog createReblog
POST /api/v1/statuses/:id/unreblog destroyReblog
POST /api/v1/statuses/:id/bookmark createBookmark
POST /api/v1/statuses/:id/unbookmark destroyBookmark
POST /api/v1/statuses/:id/mute createMute
POST /api/v1/statuses/:id/unmute destroyMute
POST /api/v1/statuses/:id/pin createPinnedStatus
POST /api/v1/statuses/:id/unpin destroyPinnedStatus
PUT /api/v1/statuses/:id updateStatus
GET /api/v1/statuses/:id/history lookupEditHistory
GET /api/v1/statuses/:id/source lookupEditableSource
GET /api/v1/scheduled_statuses lookupScheduledStatuses
GET /api/v1/scheduled_statuses/:id lookupScheduledStatus
PUT /api/v1/scheduled_statuses/:id updateScheduledStatus
DELETE /api/v1/scheduled_statuses/:id destroyScheduledStatus

1.3.6.2. v2

1.3.7. Notifications Service #

1.3.7.1. v1

Endpoint Method Name
GET /api/v1/notifications lookupNotifications
GET /api/v1/notification/:id lookupNotification
POST /api/v1/notifications/clear destroyAllNotifications
POST /api/v1/notifications/:id/dismiss destroyNotification

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 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.

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):

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

22
likes
130
points
42
downloads

Publisher

verified publishershinyakato.dev

Weekly Downloads

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

Repository (GitHub)
View/report issues
Contributing

Documentation

API reference

License

BSD-3-Clause (license)

Dependencies

freezed_annotation, http, json_annotation, universal_io

More

Packages that depend on mastodon_api