1

I'm trying to get all the questions with details from Stack Exchange API for a given user ID using following code:

response = requests.get("http://api.stackexchange.com/2.2/users/2593236/questions?")

However, I receive this error message.

{"error_id":400,"error_message":"site is required","error_name":"bad_parameter"}

Can anyone help me with this issue and retrieve all user asked questions according to their user ID?

double-beep
  • 5,031
  • 17
  • 33
  • 41
SjAnupa
  • 102
  • 10

2 Answers2

2

To download all questions or answers from a specific user and stack, you can use:

import requests, traceback, json

all_items = []
user = 2593236
stack = "stackoverflow.com"
qa = "questions" # or answers

page = 1
while 1:
    u = f"https://api.stackexchange.com/2.2/users/{user}/{qa}?site={stack}&page={page}&pagesize=100"
    j = requests.get(u).json()
    if j:

        all_items += j["items"]

        if not j['has_more']:
            print("No more Pages")
            break
        elif not j['quota_remaining']:
            print("No Quota Remaining ")
            break
    else:
        print("No Questions")
        break

    page+=1


if all_items:
    print(f"How many {qa}? ", len(all_items))
    # save questions/answers to file
    with open(f"{user}_{qa}_{stack}.json", "w") as f:
        f.write(json.dumps(all_items))

Demo

Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
  • 1
    Some suggestions: Increase the page size from the default 30 to 100 (add `&pagesize=100`). That will reduce the number of API calls. Also, should have a way to handle API errors/[backoffs](https://api.stackexchange.com/docs/throttle). – double-beep Apr 26 '20 at 19:12
  • @double-beep I added you suggestion to the answer and demo, tks! – Pedro Lobito Apr 26 '20 at 19:33
0

The error message is pretty clear: you have to include a site parameter, as explained in the documentation:

Each of these methods operates on a single site at a time, identified by the site parameter. This parameter can be the full domain name (ie. "stackoverflow.com"), or a short form identified by api_site_parameter on the site object.

Try

http://api.stackexchange.com/2.2/users/2593236/questions?site=stackoverflow.com
Nate Eldredge
  • 48,811
  • 6
  • 54
  • 82