0

I am trying to experiment with the API for my project.

I am trying to upvote a comment on the SO website to test out the API. My POST request is returning with a status code of 400.

The response -

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

I have tried putting the site parameter in the URL, using the line request_api("/comments/{id}/upvote", "site=stackoverflow.com", "POST", body); (see below code), but it said:

{"error_id":400,"error_message":"POST methods expects all parameters to be submitted as a form, not on the query string","error_name":"bad_parameter"}

Here is my code -

    let key = "{key}", base_url = "https://api.stackexchange.com";

    function request_api(path, params="", method="GET", body=""){
        let xhr = new XMLHttpRequest();
        let url;
        url = base_url + path + "?" + params;
        alert(url);
        xhr.open(method, url, false);
        xhr.setRequestHeader("Content-Type", "application/json")
        xhr.onload = function(){
            if (xhr.status >= 200 && xhr.status < 300){
                window.responseText = xhr.responseText;
            } else {
                alert("Status received is " + xhr.status);
                window.responseText = xhr.responseText;
            };
        };
        xhr.onerror = function(){
            alert("Error " + xhr.status);
            window.responseText = xhr.responseText;
        }
        if (body){
            xhr.send(body);
        } else {
            xhr.send();
        };
    };

    let body = JSON.stringify({
        access_token: login_info.access_token,
        key: key,
        site: "stackoverflow"
    });
    alert(body);
    request_api("/comments/{id}/upvote", "", "POST", body);
    document.write(window.responseText);

Edit: I looked at this post. I tried the solution there (it was the most upvoted and had a bounty). It didn't work.

Edit 2: Same thing with /questions/{id}/upvote

4
  • the access_token, key and site need to go as params on the url (eq into the second argument of your function). They should not go into the body. Commented Feb 26 at 23:36
  • I tried that before too... After some more digging it turns out that it has to be sent as application/x-www-form-urlencoded format Commented Feb 27 at 0:39
  • I might be missing something, but where do you specify the ID of the comment / post to upvote? Commented Mar 5 at 7:30
  • In the real code I replace {id} with the actual id Commented Mar 11 at 2:51

1 Answer 1

0

You need to send the POST as application/x-www-form-urlencoded format.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.