From post number to post id

Hi everybody!
I’m wondering whether there’s a way through Discourse API to get the post id from a canonical post url such as https://myweb.site/t/<topic_id>/<post_number> where of course TN is the topic id/number and PN is the post number.

I did a few tries using the post stream data from https://myweb.site/t/<topic_id>.json, thinking that, for example, post_number N would be the n-th post id in the post_stream->stream data returned by the call, but if posts were deleted or split were done in the topic posts flow, the post_number does not correspond to the n-th position in the stream.

Am I missing something obvious?

3 Likes

Have you tried /t/<topic_id>/posts.json? That will get 20 posts and you can take the post_number-th one, which will contain a post id.

But to get more that 20 you’ll need pagination, which I don’t see how to do at the moment.

2 Likes

I was in dire need of the same feature two years ago. I still have not found out how to do it (more) properly. This is my hack:

def get_topic_post(topic_id, post_num)
    topic = @api.topic(topic_id, {print: true})
    post_obj = topic['post_stream']['posts'].find { |p| p['post_number'] == post_num }
    if post_obj
        post_obj['id']
    else
        throw "Could not find post #{topic_id}/#{post_num}."
    end
end

This circumvents the mentioned issues: The {print: true} addresses the pagination issue. The find is needed as moderation can create a mismatch between array indices and post numbers.

It works for topics of the size I’m working with. Still, a more direct way through the API would feel more satisfying.

1 Like