stackexchange-api

How to get information from different objects with 1 call?


I need to have list of tags with 3 fields:

  1. tag_name

  2. tag_description

  3. counter_of_posts.

Since counter_of_posts is a field of tag-object and tag_description (excerpt) is a field of tag_wiki, how can I get needed information with one call?


Solution

  • This is impossible - you need at least 2 calls (more if you have more than 20 tags). One call to /tags/{tags}/info?site={site} to get the tag's name (which is given) and the counter and one to /tags/{tags}/wikis?site={site}. Of course, you can apply whatever filters you want and change the sitename and tag names. Here's a JavaScript sample:

    (async function() {
      const key = '3loXx7CAr2AvrMaHBj6GxQ(('; // not necessary, but it increases daily API quota from 300 to 10000
      const sitename = 'stackoverflow'; // default, change it to whatever you want
      const tags = 'php;javascript;java;jquery;perl;python'; // semicolon-separated, must be =<20
      const tagApiUrl = 'https://api.stackexchange.com/2.2/tags/';
      const tagInfoFilter = '!-.G.68pp778y';
      const tagWikisFilter = '!*Ly1)NvM)n91RtK*';
    
      // First API call: get tag's info
      const callTagInfo = await fetch(`${tagApiUrl}${tags}/info?site=${sitename}&filter=${tagInfoFilter}&key=${key}`);
      const data_counter = await callTagInfo.json();
    
      // Second API call: get tag's excerpt
      const callTagWikis = await fetch(`${tagApiUrl}${tags}/wikis?site=${sitename}&filter=${tagWikisFilter}&key=${key}`);
      const data_excerpt = await callTagWikis.json();
    
      for (let i = 0; i < data_counter.items.length; i++) {
        const table = document.querySelector('table');
        const html = `
          <tr>
            <td>${data_counter.items[i].name}</td>
            <td>${data_excerpt.items.find(name => name.tag_name === data_counter.items[i].name).excerpt}</td>
            <td>${data_counter.items[i].count}</td>
          </tr>`;
         table.insertAdjacentHTML('beforeend', html);
      }
      console.log('API Quota remaining:', data_excerpt.quota_remaining);
    })();
    <link rel="stylesheet" href="https://unpkg.com/@stackoverflow/stacks/dist/css/stacks.min.css">
    <table class="s-table">
      <tbody>
        <tr>
          <th>Tag Name</th>
          <th>Excerpt</th>
          <th>Number of posts</th>
        </tr>
      </tbody>
    </table>