As my distaste for Twitter has grown over the last while I decided to see if I could deploy my own instance of Mastodon, a federated, distributed social network. Turns out I had my instance up and running in just a few hours using a $10 a month Digital Ocean Docker droplet and the handy Mastodon docker containers. It was way easier than I though it would be.
One of the first things I wanted to do with my instance was use the API to auto-post to my Mastodon feed whenever I post anything here on the site. I was doing it with Twitter so I wanted to do it with Mastodon as well. My first attempt at it didn’t go so well, downloading a wrapper framework that hadn’t been updated in a year and failing to get it to work.
Turns out I was overthinking the whole thing. Since I wasn’t creating an app for multiuple users, all I needed was good ol’ cURL and some access tokens. Here’s what I did to make it all work.
Step One #step-one
Login to your Mastodon instance. Click on the Settings icon, then click on the Development tab.
Click the New Application button. In the form, give your application a name, a website URL (mine is just my homepage), and leave the Redirect URI and Scopes sections with the defaults. Hit the Submit button. This should save your new application details and give you three keys: Client key, Client secret, and Your access token. As the warning says, don’t share these with anyone!
Step Two #step-two
Now that you have your access token, you can use that in an authorization header. Now all you need to do is assemble your cURL options in PHP and send the request. Here’s an example to post a status message, with my access key and API endpoint URL removed:
$headers = [ 'Authorization: Bearer [YOUR ACCESS TOKEN GOES HERE]' ]; $status_data = array( "status" => "Posting to Mastodon!", "language" => "eng", "visibility" => "public" ); $ch_status = curl_init(); curl_setopt($ch_status, CURLOPT_URL, "[YOUR MASTODON INSTANCE URL]/api/v1/statuses"); curl_setopt($ch_status, CURLOPT_POST, 1); curl_setopt($ch_status, CURLOPT_POSTFIELDS, $status_data); curl_setopt($ch_status, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch_status, CURLOPT_HTTPHEADER, $headers); $output_status = json_decode(curl_exec($ch_status)); curl_close ($ch_status);
That’s all #that’s-all
From here you can most likely figure out how to post media using a similar process. With media though you need to make two requests: one to send the media and get media ID’s back, and the second a new status request that includes the media ID’s. Maybe I’ll do a post on that too!