Once again I have been looking at the Bluesky API as part of a question posted on my Github respository. This time the question was “Can I specify one URL and use PHP to retrieve only one bluesky post by someone else?”. You don’t actually need my library to do that but I thought it would be useful to post details here as it’s not immediately obvious.
Identifying an Individual Post
The first thing to consider is how to identfy an individual post. Consider that we want to retrieve the following post progamatically.
Looking at the URL for this page it takes the following form:
https://bsky.app/profile/spokenlikeageek.com/post/3kimiqbm6od2i
This URL contains two important pieces of information that we need. These are the Bluesky account name (spokenlikeageek.com in this case) and the post id (3kimiqbm6od2i here). Both are needed to retrieve this post programatically.
Let’s write a quick bit of code to extract the information we need from a URL.
$url = "https://bsky.app/profile/spokenlikeageek.com/post/3kimiqbm6od2i";
// Extract the account name
preg_match('/\/([^\/]+)\/([^\/]+)\/([^\/]+)/', $url, $matches);
$account = isset($matches[3]) ? $matches[3] : '';
// Extract the post id
preg_match_all('/\/([^\/]+)/', $url, $matches);
$postId= isset($matches[1][4]) ? $matches[1][4] : '';
We now have the information we need held in $account and $postId which we will use in the examples below.
Two Approaches
Now that we have this information we can use it to retrieve the post. To do that we need to use the com.atproto.repo.getRecord
method in the Bluesky api.
The first way that we can do this is to do a direct call over https as follows:
$post = json_decode(file_get_contents("https://bsky.social/xrpc/com.atproto.repo.getRecord?repo=$account&collection=app.bsky.feed.post&rkey=$postId"));
The alternative, if you are using Clark Rasmussen’s library, is as follows:
// connect to Bluesky API
$connection = bluesky_connect($handle, $password);
$args = [
'repo' => $account,
'collection' => 'app.bsky.feed.post',
'rkey' => $postId
];
// retrieve the post from Bluesky using the extracted account name and post id
$post = $connection->request('GET', 'com.atproto.repo.getRecord', $args);
In both cases the output is an array that contains the information that is show in the image at the top of this post.
Updating the Library
As I said above you don’t actually need my library to retrieve a post from Bluesky but given that it is a useful thing to do I have added in a function called get_from_bluesky
to which you pass a connection string and a url and get back the post as an array. You can get the latest code from my Github repository.