3

So, I made a query using Stack Exchange Data Explorer:

SELECT TOP 100 Id 
AS [Post Link], 
ViewCount,
AnswerCount,
FavoriteCount,
CommentCount,
Score,
Tags

FROM Posts
ORDER BY ViewCount DESC

It returns just what I need, but I need to retrieve this by a python script.

Using the StackAPI, I can retrieve the questions, but I can't sort it by view_count.

I was trying to retrieve to the API like that:

from stackapi import StackAPI

SITE = StackAPI('stackoverflow')
SITE.max_pages=1
top_viewed_questions = SITE.fetch('questions', sort='view_count', order='desc')

print(top_viewed_questions)

But it looks like view_count can't be sorted. Am I sorting wrong the view_count or there's no way I can do that?

double-beep
  • 5,031
  • 17
  • 33
  • 41
atokzz
  • 63
  • 3
  • 1
    You can't sort on `view_count`, you can check this URL: https://api.stackexchange.com/docs/questions , scoll to the bottom there you will find all the sort options that you can use. – Mushif Ali Nawaz May 14 '20 at 06:27
  • 1
    Oh. I see it now. Thanks for showing where I can see what I can use to sort! – atokzz May 14 '20 at 06:30
  • 1
    The first SQL query comes from https://data.stackexchange.com which is updated every Sunday. The API is real-time and fairly better. – double-beep May 14 '20 at 09:33
  • Good to know, I thought that the data in data.stackexchange.com was updated everyday. So it really looks like I should use the API then. Thanks. – atokzz May 14 '20 at 11:20
  • How about fetching the questions you want, store them in an array and sort them? – double-beep May 14 '20 at 12:28
  • The problem is I only wanted the top 100 most viewed posts. To be able to fetch the questions and sort them by view count correctly, I think I would have to retrieve all questions from the site, sort them by view count and select the first 100 which is impossible. – atokzz May 14 '20 at 12:39
  • How about fetching https://stackoverflow.com/questions/greatest-hits, then find questions in the API and sort by view count? These *must* be the questions with the highest view count. Oh, and why don't you use SQL Data Explorer? While it's updated weekly, the first 100 questions will not change for a period of time. – double-beep May 14 '20 at 18:47
  • Yeah. It is a fact that the first 100 questions won't change, but my teacher asked us to fetch the questions by code, so I couldn't use the SQL Data Explorer. I will look into fetching stackoverflow.com/questions/greatest-hits as you said, it looks like a nice way out to my problem, as I think it will really retrieve the most viewed questions. Thanks again bro! :) – atokzz May 15 '20 at 01:20
  • [Here](https://pastebin.com/MNi5Gh3W) is a piece of code that will help you get all the questions' ids, stored in the `ids` array. Pass those to the API (semicolon-separated, max 100 at once) and get the *exact* view count. If you need help, ping me ;) – double-beep May 15 '20 at 08:21

0 Answers0