3

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?

double-beep
  • 5,031
  • 17
  • 33
  • 41
vsync
  • 118,978
  • 58
  • 307
  • 400
  • 7
    I dont believe this is possible - one reason being usernames are not unique. – karthikr Sep 21 '14 at 21:43
  • so what, so why can't I get all the ID's possible per username, and if it's a unique one, use that. – vsync Sep 21 '14 at 21:44
  • While that may be an idea, it is not a standard/intuitive way of implementing an API. Here: https://api.stackexchange.com/docs/ are a list of all the api end points, and looks like it supports only ids.. – karthikr Sep 21 '14 at 21:49
  • that should be an API by itself, to get all IDs related to a user name. but they didn't do that for some reason, so I am forced to hack a solution myself... – vsync Sep 21 '14 at 21:50

1 Answers1

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


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>
double-beep
  • 5,031
  • 17
  • 33
  • 41
vsync
  • 118,978
  • 58
  • 307
  • 400