Using Mastodon V2 API without a user token?

121 views Asked by At

I am trying to use the Mastodon V2 search API on mastodon.social from python(3), to search for a specific hashtag used in a specific account. Here is the bare-bones skeleton of code I am using:

import requests

url = 'https://mastodon.social/api/v2/search'
params = {'q': '<hashtag to search for>', 'type':'hashtags', 'account_id':'<my account id>'}

response = requests.get(url, data=params)

print(response)

I am not supplying a user-token. According to the documentation at https://docs.joinmastodon.org/methods/search/, I should be able to do so:

4.0.0 - no longer requires a user token. Without a valid user token, you cannot use the resolve or offset parameters.

Given that mastodon.social is running at least 4.1.4, I think this should be possible.

However, I get a Bad Request <Response [400]> no matter what I try. I am not sure where to go from here, what am I doing wrong?

1

There are 1 answers

0
gorby On

It looks like I was filling out the request wrong, I should have used params instead of data.

Also, I needed to add a header, so the full example should instead look like

import requests

url = 'https://mastodon.social/api/v2/search'

headers = { 'Content-Type': 'application/x-www-form-urlencoded' }
params = {'q': '<hashtag to search for>', 'type':'hashtags', 'account_id':'<my account id>'}

response = requests.get(url, params=params, headers=headers)

print(response)

And to get the payload from the response:

print(response.text)

Additionally, use json to get the structured data:

import json

data = json.loads(response.text)