I tried hitting Mastodon API with Ruby (Faraday) / Python (Pycurl) / PHP (Curl)

I tried hitting Mastodon for the time being. As the title suggests, Ruby uses Faraday, Python uses Pycurl, and PHP uses Curl. I registered the application with app.xx, and authenticated with test.xx ~ Posting flow.

Ruby

app.rb


#!/usr/local/bin/ruby
# -*- coding: utf-8 -*-

require 'faraday'
require 'uri'

CALLBACK_URL = 'App URL'
MASTODON_URL = 'URL of the target instance (eg: https://mstdn.high-low.ml)'
SCOPE = 'Privileges you want (eg: read write)'

options = {
  client_name: 'App name',
  redirect_uris: CALLBACK_URL,
  scopes: SCOPE
}

conn = Faraday.new(:url => MASTODON_URL) do |faraday|
  faraday.request :url_encoded
  faraday.response :logger
  faraday.adapter Faraday.default_adapter
end
response = conn.post do |request|
  request.url '/api/v1/apps'
  request.body = URI.encode_www_form(options)
end
print "Content-Type: application/json; charset=UTF-8\n\n"
print response.body

Save the "client_id" and "client_secret" displayed in the output result.

test.rb


#!/usr/local/bin/ruby
# -*- coding: utf-8 -*-

require 'cgi'
require 'uri'

cgi = CGI.new()

CALLBACK_URL = 'App URL'
MASTODON_URL = 'URL of the target instance'
CLIENT_ID = 'app.CLIENT obtained by rb_ID'
CLIENT_SECRET = 'app.CLIENT obtained by rb_SECRET'
SCOPE = 'Specified authority'

if cgi['code'].empty?
  #Go get the certification
  options = {
    client_id: CLIENT_ID,
    response_type: 'code',
    scope: SCOPE,
    redirect_uri: CALLBACK_URL
  }
  print cgi.header({
    'status' => 'REDIRECT',
    'Location' => "#{MASTODON_URL}/oauth/authorize?#{URI.encode_www_form(options)}"
  })
else
  #Authenticated so access_I'm going to get a token
  require 'faraday'
  require 'json'

  options = {
    client_id: CLIENT_ID,
    client_secret: CLIENT_SECRET,
    grant_type: 'authorization_code',
    redirect_uri: CALLBACK_URL,
    scope: SCOPE,
    code: cgi['code']
  }

  conn = Faraday.new(:url => MASTODON_URL) do |faraday|
    faraday.request :url_encoded
    faraday.response :logger
    faraday.adapter Faraday.default_adapter
  end
  response = conn.post do |request|
    request.url '/oauth/token'
    request.body = URI.encode_www_form(options)
  end
  access_token = JSON.parse(response.body)['access_token']

  # access_While I got the token, I scream in the center of the world
  options = {
    mastodon_host: MASTODON_URL,
    status: 'Paon'
  }
  response = conn.post do |request|
    request.url '/api/v1/statuses'
    request.headers = {
      'Authorization' => "Bearer #{access_token}"
    }
    request.body = URI.encode_www_form(options)
  end
  print "Content-Type: application/json; charset=UTF-8\n\n"
  print response.body
end

The authentication screen looks like this. スクリーンショット 2017-04-19 17.37.07.png

Python

app.py


#!/usr/bin/python
# -*- coding: utf-8 -*-

import pycurl, urllib
from StringIO import StringIO

CALLBACK_URL = 'App URL'
MASTODON_URL = 'URL of the target instance'
SCOPE = 'Privileges you want (eg: read write)'

options = {
	'client_name': 'App name',
	'redirect_uris': CALLBACK_URL,
	'scopes': SCOPE
}

response = StringIO()
curl = pycurl.Curl()
curl.setopt(pycurl.URL, '%s/api/v1/apps' %(MASTODON_URL))
curl.setopt(pycurl.WRITEFUNCTION, response.write)
curl.setopt(pycurl.POST, 1)
curl.setopt(pycurl.POSTFIELDS, urllib.urlencode(options))
curl.perform()
print "Content-Type: application/json; charset=UTF-8\n\n"
print response.getvalue()

test.py


#!/usr/bin/python
# -*- coding: utf-8 -*-

import urllib, cgi
from StringIO import StringIO

form = cgi.FieldStorage()

CALLBACK_URL = 'App URL'
MASTODON_URL = 'URL of the target instance'
CLIENT_ID = 'app.CLIENT obtained by py_ID'
CLIENT_SECRET = 'app.CLIENT obtained by py_SECRET'
SCOPE = 'Specified authority'

if not form.has_key('code'):
	#I'm going to get the certification
	options = {
		'client_id': CLIENT_ID,
		'response_type': 'code',
		'scope': SCOPE,
		'redirect_uri': CALLBACK_URL
	}
	print "Content-Type: text/html\n\n"
	print '<meta http-equiv=\"refresh\" content=\"0; URL=%s/oauth/authorize?%s\">' %(MASTODON_URL, urllib.urlencode(options))
else:
	# access_I'm going to get a token
	import pycurl, json

	options = {
		'client_id': CLIENT_ID,
		'client_secret': CLIENT_SECRET,
		'grant_type': 'authorization_code',
		'redirect_uri': CALLBACK_URL,
		'scope': SCOPE,
		'code': form['code'].value
	}

	response = StringIO()
	curl = pycurl.Curl()
	curl.setopt(pycurl.URL, '%s/oauth/token' %(MASTODON_URL))
	curl.setopt(pycurl.WRITEFUNCTION, response.write)
	curl.setopt(pycurl.POST, 1)
	curl.setopt(pycurl.POSTFIELDS, urllib.urlencode(options))
	curl.perform()
	access_token = str(json.loads(response.getvalue())['access_token'])

	#Shout
	options = {
		'mastodon_host': MASTODON_URL,
		'status': 'Paon'
	}

	curl.setopt(pycurl.URL, '%s/api/v1/statuses' %(MASTODON_URL))
	curl.setopt(pycurl.HTTPHEADER, ['Authorization: Bearer %s' %(access_token)])
	curl.setopt(pycurl.POSTFIELDS, urllib.urlencode(options))
	curl.perform()

	print "Content-Type: application/json; charset=UTF-8\n\n"
	print response.getvalue()

PHP

app.php


<?php
define('CALLBACK_URL', 'App URL');
define('MASTODON_URL', 'URL of the target instance (eg: https://mstdn.high-low.ml)');
define('SCOPE', 'Privileges you want (eg: read write)');

$options = array(
	'client_name' => 'App name',
	'redirect_uris' => CALLBACK_URL,
	'scopes' => SCOPE
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, MASTODON_URL. '/api/v1/apps');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $options);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$response = curl_exec($ch);
curl_close($ch);

header('Content-type: application/json; charset=utf-8');
echo $response;

test.php


<?php
define('CALLBACK_URL', 'App URL');
define('MASTODON_URL', 'URL of the target instance');
define('CLIENT_ID', 'app.CLIENT obtained by php_ID');
define('CLIENT_SECRET', 'app.CLIENT obtained by php_SECRET');
define('SCOPE', 'Specified authority');

if (!isset($_GET['code'])) {
	#Authentication
	$options = array(
		'client_id' => CLIENT_ID,
		'response_type' => 'code',
		'scope' => SCOPE,
		'redirect_uri' => CALLBACK_URL
	);
	header('Location: '. MASTODON_URL. '/oauth/authorize?'. http_build_query($options, '', '&'));
} else {
	# access_get token
	$options = array(
		'client_id' => CLIENT_ID,
		'client_secret' => CLIENT_SECRET,
		'grant_type' => 'authorization_code',
		'redirect_uri' => CALLBACK_URL,
		'scope' => SCOPE,
		'code' => $_GET['code']
	);

	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, MASTODON_URL. '/oauth/token');
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $options);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	$response = curl_exec($ch);
	$data = json_decode($response);
	$access_token = $data->access_token;

	#Paon
	$options = array(
		'mastodon_host' => MASTODON_URL,
		'status' => 'Paon'
	);

	curl_setopt($ch, CURLOPT_URL, MASTODON_URL. '/api/v1/statuses');
	curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: Bearer {$access_token}"));
	curl_setopt($ch, CURLOPT_POSTFIELDS, $options);
	$response = curl_exec($ch);
	curl_close($ch);
	header('Content-type: application/json; charset=utf-8');
	echo $response;
}

reference

tootsuite/mastodon-api: A ruby interface for the Mastodon API Sample of hitting Mastodon's API with curl --Qiita How to hit the Mastodon API

Recommended Posts

I tried hitting Mastodon API with Ruby (Faraday) / Python (Pycurl) / PHP (Curl)
I tried using mecab with python2.7, ruby2.3, php7
I tried hitting the API with echonest's python client
PHP / Python / Ruby sample hitting Path API
I tried fp-growth with python
I tried gRPC with Python
I tried scraping with python
I tried using the Python library from Ruby with PyCall
I tried follow management with Twitter API and Python (easy)
Dynamic proxy with python, ruby, PHP
I tried web scraping with python.
I tried running prolog with python 3.8.2.
I tried SMTP communication with Python
I tried ChatOps with Slack x API Gateway x Lambda (Python) x RDS
I tried hitting the Google API with Ruby and Python-Make the database a Spreadsheet and manage it with Google Drive
Realize PHP / Python generator with Golang / Ruby
I tried scraping Yahoo News with Python
I tried sending an email with python.
I tried non-photorealistic rendering with Python + opencv
I tried a functional language with Python
I tried recursion with Python ② (Fibonacci sequence)
#I tried something like Vlookup with Python # 2
I tried to get the authentication code of Qiita API with Python.
I tried to get the movie information of TMDb API with Python
I tried "smoothing" the image with Python + OpenCV
I tried hundreds of millions of SQLite with python
I tried hitting the Qiita API from go
I tried "differentiating" the image with Python + OpenCV
I tried "License OCR" with Google Vision API
I tried to automate internal operations with Docker, Python and Twitter API + bonus
I tried Jacobian and partial differential with python
I tried to get CloudWatch data with Python
I tried function synthesis and curry with python
I tried to output LLVM IR with Python
I tried "binarizing" the image with Python + OpenCV
I tried to automate sushi making with python
I tried playing mahjong with Python (single mahjong edition)
I tried "Receipt OCR" with Google Vision API
I tried sending an email with SendGrid + Python
I tried to get started with blender python script_Part 01
I tried to touch the CSV file with Python
I tried to draw a route map with Python
[OpenCV / Python] I tried image analysis of cells with OpenCV
I tried to get started with blender python script_Part 02
I tried to implement an artificial perceptron with python
I tried to automatically generate a password with Python3
Mayungo's Python Learning Episode 1: I tried printing with print
I tried to solve the problem with Python Vol.1
I moved the automatic summarization API "summpy" with python3.
I tried "morphology conversion" of images with Python + OpenCV
I tried to solve AOJ's number theory with Python
I tried Python> autopep8
I tried Python> decorator
I tried deploying Kubernetes Pods / Helm Chart with Pulumi (Python)
I tried to find the entropy of the image with python
Try hitting the Twitter API quickly and easily with Python
I tried "gamma correction" of the image with Python + OpenCV
I tried to simulate how the infection spreads with Python
A note about hitting the Facebook API with the Python SDK
I tried to create API list.csv in Python from swagger.yaml
I tried to make various "dummy data" with Python faker