Skip to content Skip to sidebar Skip to footer

How Can I Get A User's Id Given Their Username From The Stack Exchange Api?

I want to fetch a user's activity on Stack Overflow, using the /users/{ids}/timeline method. The problem is that this method only accepts a user id, yet I want to pass a username,

Solution 1:

I hacked my way by scraping the response from the /users endpoint with help of YQL for getting the page by AJAX cross-domain.

Here's the rough code (JS Bin):

const idCont = $('div');
const input = $('input');

// input events
input.on('blur', function() {
  doAjax(this.value);
}).on('keydown', function(e) {
  if (e.keyCode == 13)
    doAjax(this.value);
});


functiondoAjax(url) {
  url = 'http://stackoverflow.com/users/filter?search=' + url;
  if (url.match('^http')) {
    idCont.html('fetching...');
    $.getJSON("http://query.yahooapis.com/v1/public/yql?" +
      "q=select%20*%20from%20html%20where%20url%3D%22" +
      encodeURIComponent(url) +
      "%22&format=xml'&callback=?",
      function(data) {
        idCont.empty();
        if (data.results[0]) {
          data = filterData(data.results[0]);
          getIDs($('<div>').html(data));
        }
      }
    );
  }
}

// clean up the responsefunctionfilterData(data) {
  data = data.replace(/<?\/body[^>]*>/g, '')
    .replace(/[\r|\n]+/g, '')
    .replace(/<--[\S\s]*?-->/g, '')
    .replace(/<noscript[^>]*>[\S\s]*?<\/noscript>/g, '')
    .replace(/<script[^>]*>[\S\s]*?<\/script>/g, '')
    .replace(/<script.*\/>/, '');
  return data;
}

// scrap the DOM for the user's IDsfunctiongetIDs(elm) {
  var IDs = '';
  elm.find('.user-info').each(function() {
    var id = $(this).find('a:first')[0].href.split('/').reverse()[1];
    IDs += id + '<br>';
  });

  idCont.html(IDs);
}
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><input><div></div>

Post a Comment for "How Can I Get A User's Id Given Their Username From The Stack Exchange Api?"