Skip to content

Instantly share code, notes, and snippets.

@jmsdnns
Last active August 11, 2024 16:46
Show Gist options
  • Save jmsdnns/cdd856075d10b3454282f5579c12bb8c to your computer and use it in GitHub Desktop.
Save jmsdnns/cdd856075d10b3454282f5579c12bb8c to your computer and use it in GitHub Desktop.
Some simple code to fetch toots from the Mastodon API
use tokio;
use reqwest;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug)]
struct Account {
username: String
}
#[derive(Serialize, Deserialize, Debug)]
struct Status {
id: String,
content: String,
created_at: String,
account: Account
}
#[derive(Serialize, Deserialize, Debug)]
struct APIResponse {
statuses: Vec<Status>,
}
async fn mastodon_search(
client: &reqwest::Client,
token: &str,
query: &str,
) -> Result<APIResponse, reqwest::Error> {
let url = "https://mastodon.social/api/v2/search";
let params = [("q", query), ("type", "statuses"), ("limit", "5")];
let response = client
.get(url)
.bearer_auth(&token)
.query(&params)
.send()
.await?;
Ok(response.json::<APIResponse>().await?)
}
#[tokio::main]
async fn main() -> Result<(), reqwest::Error> {
let client = reqwest::Client::new();
let token = "<a mastodon token>";
let query = "musodon";
let body = mastodon_search(&client, &token, &query).await?;
for s in body.statuses.iter().collect::<Vec<&Status>>() {
let s: &Status = s;
println!("{} {}\n{}\n", s.account.username, s.created_at, s.content);
}
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment