LoginSignup
15
9

More than 5 years have passed since last update.

ブラウザのみでmastodonのAPIを叩く方法

Last updated at Posted at 2017-04-21

ブラウザのみでmastodonのAPIを叩く方法

連携access tokenは予め取得してあるものとします。
キモは、リクエストヘッダの Authorization でaccess tokenを送ることです。
あとは普通にAPIのエントリを叩けば、JSONで取得することができます。

    var access_token = "xxxxxxx" ;
    var path = "https://mstdn.jp/api/v1/timelines/home" ;
    var req = new XMLHttpRequest();
    req.open("get",path,true) ;
    req.responseType = "json" ;
    req.setRequestHeader("Authorization","Bearer "+access_token ) ;
    req.onload = function() {
        console.log( this.response );
        console.log( this.getResponseHeader("Link") ) ; 
    }
    req.onerror = function() {
        console.log(this);
    }
    req.send() ;

(あ、もちろん公開ページにaccess tokenを埋めこんだりしたらだめですよ)

タイムラインAPIでは最大最新40件までとれるので、それ以外は、max_id,since_idのパラメータを付けて取得できます。
また、レスポンスヘッダの"Link"に次と前を取得するリンクが帰ってくるので、getResponseHeaderを使って取得するといいでしょう。

<https://mstdn.jp/api/v1/timelines/home?max_id=2175080>; rel="next", <https://mstdn.jp/api/v1/timelines/home?since_id=2192302>; rel="prev"

のような感じで入ってきます。

実際にAPIを試してみることのできるページを作りました。

access tokenの取得の仕方は、以下等を参考に。

http://qiita.com/albno273/items/eb109820125faf7638cd
http://qiita.com/syui/items/b6d07958cc9acf1b9fdc

こちらのWebアプリでも簡単にaccess tokenを取得することができます。
https://takahashim.github.io/mastodon-access-token/

APIのドキュメント(本家)は、
https://github.com/tootsuite/documentation/blob/master/Using-the-API/API.md

です。

15
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
9