vsync
vsync

Reputation: 130471

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, so anybody could just write their nickname and get the relevant stats. The API doesn't seem to support getting a user id by supplying the username either.

Is there any workaround to get a user's id given their username?

Upvotes: 2

Views: 509

Answers (1)

vsync
vsync

Reputation: 130471

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);
});


function doAjax(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 response
function filterData(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 IDs
function getIDs(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);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input>
<div></div>

Upvotes: 1

Related Questions