How to get more posts from posts.json

(Raymon Mens) #1

Hi guys,

I’m trying to integrate Discourse in another front-end and would like to show the latest posts on the frontpage. Im querying the API with for example but don’t get a consistent amount of posts back.

Is there any way to show the latest n posts. I tried and but none of that is working.


(Swarnava) #2

There is something like that to fetch the latest posts:

(Dalmiro Grañas) #3

@swarnava what is the difference between /lastest.json and /posts.json?

Edit after actually testing instead of just asking :slight_smile: :

  • /latest.json returns the latest Topics
  • /posts.json returns the latest Posts

Is there a way to filter any of those by date? I’m also integrating Discourse with another tool, and I need to do “Give me all posts since (Now -7 days)”

(Raymon Mens) #4

It’s also still not clear to me how to get the latest n posts, not topics.

(Dalmiro Grañas) #5

So the questions we have with @rmens are:

  • How far back in time/amount of posts does /posts.json get you?
  • Is this configurable in any way from the API call?


This thread looks promising: Latest posts API pagination

I’ll post my findings tomorrow after testing this a bit more

(Dalmiro Grañas) #6

/posts.json?before=X returns the first 50 posts with an ID lower than X. So if you want the get the lastest 75 posts for example, you can do:

  1. GET /posts.json to get the last 50
  2. GET /posts.json?before=x where x is the ID of the oldest post in the set of the previous GET call.
  3. Get the first 25 posts of this last GET set and you’ll have the 75 you wanted.

In my case I needed all the posts from the last 24hs, so my code looks like:

  1. GET /posts.json to get the last 50.
  2. If the oldest post in the set returned by the previous GET was created between the last 24hs, I do GET /posts.json?before=x where x is the ID of the oldest post in the set of the previous GET call.
  3. Repeat until the GET call returns at least 1 post that was created more than 24hs ago.

Hope this helps anyone :slight_smile:

(Kane York) #7

You got it, that’s how that endpoint is supposed to be used :slight_smile: (although you can just do +/-50 for pages after the 2nd)

And, if you run the script again, and know what number you stopped/started at…

(Raymon Mens) #8

This helped a lot. Thanks guys!