1

I want to get the list of questions based on tag name using .Net. can any one please let me know how to achieve this using .Net with API Version 2.2?

1 Answer 1

5

To get the questions in a tag you can simply use the /questions endpoint as that does accept a tagged query parameter, from that document page:

To constrain questions returned to those with a set of tags, use the tagged parameter with a semi-colon delimited list of tags. This is an and contraint ...

The API endpoints can relatively simple be used from any language which offer a web- or httpclient. First thing to do is the creation of the correct url and then process the returned http response. When using the HtppClient and the stock DataContractJsonSerializer your first iteration of a .Net 4.5 console app (VS2015) might look like this:

using System;
using System.Net.Http;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;

main method

static void Main(string[] args)
{
    // simple call with a tagname
    var questions = GetQuestions("haskell");
    // list the results
    Console.WriteLine(String.Format("{0}, \"{1}\", \"{2}\"", "id", "title", "link"));
    foreach (var q in questions.items)
    {
        Console.WriteLine(String.Format("{0}, \"{1}\", \"{2}\"", q.question_id, q.title, q.link));
    }
}

GetQuestions

Builds the url, calls the API and Deserialises the result to .Net classes

private static wrapper<Question> GetQuestions(string tagname)
{
    // make sure to handle the compressed stream that is returned
    using (var handler = new HttpClientHandler
        {
            AutomaticDecompression = System.Net.DecompressionMethods.Deflate 
                                   | System.Net.DecompressionMethods.GZip
        })
    {
        using (var http = new HttpClient(handler))
        {
        // build url obtained from 
        // https://api.stackexchange.com/docs/questions#order=desc&sort=activity&tagged=haskell&filter=default&site=stackoverflow&run=true
            var apiRequest = new UriBuilder();
            apiRequest.Scheme = "https";
            apiRequest.Host = "api.stackexchange.com";
            apiRequest.Path = "2.2/questions";
            apiRequest.Query = String.Format(
              "order=desc&page=1&pagesize=10&sort=activity&tagged={0}&site=stackoverflow", 
              tagname);
            // do an HTTP GET
            var json = http.GetStreamAsync(apiRequest.Uri).Result;
            // Deserialize the resut with a serializer
            // You can also use JSON.NET
            var serializer = new DataContractJsonSerializer(typeof(wrapper<Question>));
            // cast the result
            return (wrapper<Question>)serializer.ReadObject(json);
        }
    }
}

Data Transfer Objects

These are the classes that will hold the result after deserializing the response stream:

/// <summary>
/// https://api.stackexchange.com/docs/wrapper
/// </summary>
/// <typeparam name="T">a type that be in items</typeparam>
[DataContract]
public class wrapper<T>
{
    [DataMember]
    public List<T> items { get; set;}

    [DataMember]
    public string error_message { get; set; }
    [DataMember]
    public int backoff { get; set; }
}

/// <summary>
/// https://api.stackexchange.com/docs/types/question
/// </summary>
[DataContract]
public class Question
{
    [DataMember]public int question_id { get; set; }
    [DataMember]
    public string title { get; set; }
    [DataMember]
    public string link { get; set; }
}

You can create a specific filter if you want to reduce or broaden the default fields you get returned for each question. The field in that list marked with a green check mark are delivered by default. To also have the date a post was created you only have to add a new property to the Question datacontract.

[DataMember]
public string creation_date { get; set; }

You might want to try a DateTime there but if the serializer doesn't accept that do the parsing of that creation_date yourself. On Stack Overflow you'll find plenty of examples how to so that.

5
  • Hi Rene, Thank you so much for your response. Its worked as expected.
    – Melody
    Jun 10, 2016 at 7:24
  • How to Get all the questions instead of getting page wise? For ex order=desc&page=1&sort=activity&tagged={0}&site=stackoverflow in this we are getting questions from page 1. i need to get all the questions from all pages
    – Melody
    Jun 14, 2016 at 7:22
  • You could add an extra parameter pageNr and then replace page=1 with page={1}. The wrapper json has a boolean has_more so you add that to the wrapper class and then iterate unitl has_more == false. You might want to take backoff also into account so you can do a Thread.Sleep(backoff*1000); in your loop to prevent being throttled/ blocked.
    – rene
    Jun 14, 2016 at 8:52
  • How to get created date of particular question using SO API v 2?
    – Melody
    Jul 11, 2016 at 5:44
  • @Melody just add it to the datacontract, if you don;t have a specific filter
    – rene
    Jul 11, 2016 at 7:37

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .