I'm trying to extract a random posting from a random
subreddit
in one api call, and I can't figure out how. Is this possible, and if not, how would I accomplish this with multiple api calls and minimum overhead?
The following request returns a random subreddit
.
http://www.reddit.com/r/random.json
Contrary to what one might expect from the json
extension, the data returned from the call is a complete webpage with markup, which is not what I want. The same request with an actual subreddit
is shown below.
http://www.reddit.com/r/apple.json
This request yields the apple subreddit
in json
format. In order to retrieve 5 postings from the apple subreddit
the following api call can be made.
http://www.reddit.com/r/apple/comments.json?limit=5
I figured I could apply the above api call to the random
url - as shown below.
http://www.reddit.com/r/random/comments.json?limit=5
This works as expected, yet the result is not in json
format. It is a complete webpage with markup.
Links: The reddit API
Update
In the time since my original response, /r/random has been updated to preserve extensions, so you can also now avoid having to manually process the Location
header:
$ curl http://www.reddit.com/r/random.json
{
"data": {
"after": "t3_1ubf3e",
...
Original response
http://www.reddit.com/r/random results in a redirect to a random subreddit, but does not preserve extensions. At this time, the best way to achieve your goal would be to examine the response for the Location:
header, and then perform a request to the JSON endpoint for that subreddit.
For example, using curl:
$ curl --include http://www.reddit.com/r/random
HTTP/1.1 302 Moved Temporarily
Location: http://www.reddit.com/r/cocktails/
...
reddit says you should checkout the "cocktails" subreddit, so request the JSON data for that subreddit:
$ curl http://www.reddit.com/r/cocktails/.json
{
"data": {
"after": "t3_1ubf3e",
...