API wrapper - Hope this helps somebody

I know most here have a decent understanding on what the twitch api is and what it does etc. This post is more of a “helper” for those that are struggling and want to get into the api and get going asap.

This is my personal c# twitch api wrapper.

Basically, it outputs the json ready to be used. It’s extendable too should you think of other things to put into it (i know i have). Nevertheless. I will give you guys the code and then explain it. I’ve commented out the methods so I won’t really explain them.

class TwitchAPIWrapper
{

    /// <summary>
    /// Returns List<typeparamref name="T"> containing serialized json data"/>
    /// From the Twitch.tv API
    /// </summary>
    /// <typeparam name="T">Json Root Object (do not include list<>)</typeparam>
    /// <param name="query">Query to the API as a string</param>
    /// <returns></returns>
    public static List<T> rootSerialize<T>(string query)
    {
        HttpWebRequest outboundRequest          = (HttpWebRequest)WebRequest.Create(query);
        outboundRequest.Headers["Client-ID"]    = Properties.TwitchAPISettings.Default.api_clientID; //*.settings file with required id, either remove this or replace the call with your own cid
        HttpWebResponse inboundResponse         = (HttpWebResponse)outboundRequest.GetResponse();

        saveRequest(query);

        using (StreamReader stream = new StreamReader(inboundResponse.GetResponseStream()))
        {
            using (JsonTextReader reader = new JsonTextReader(stream))
            {
                List<T> outputData = new List<T>();
                while (reader.Read())
                {
                    JsonSerializer serializer = new JsonSerializer();
                    var tempData = serializer.Deserialize<T>(reader);
                    outputData.Add(tempData);
                }
                inboundResponse.Close();
                return outputData;
            }
        }
    }

    /// <summary>
    /// ***DEPRECIATED*** Legacy command for rootSerialize
    /// Left for backwards support to 3 calls. Will Remove later
    /// </summary>
    /// <typeparam name="T">Json Root Object (Do not include List<>)</typeparam>
    /// <param name="reader">Json Text Reader</param>
    /// <returns></returns>
    public static List<T> rootSerialize<T>(JsonTextReader reader)
    {
        List<T> outputData = new List<T>();
        while (reader.Read())
        {
            JsonSerializer serializer = new JsonSerializer();
            var tempData = serializer.Deserialize<T>(reader);
            outputData.Add(tempData);
        }
        reader.Close();
        return outputData;
    }

    /// <summary>
    /// Returns LAST KNOWN raw string of a call to the Twitch.tv API
    /// </summary>
    /// <returns></returns>
    public static string getRawData()
    {
        var outboundRequest = (HttpWebRequest)WebRequest.Create(getRequest());
        outboundRequest.Headers["Client-ID"] = Properties.TwitchAPISettings.Default.api_clientID; //same deal
        var inboundResponse = (HttpWebResponse)outboundRequest.GetResponse();

        using (StreamReader stream = new StreamReader(inboundResponse.GetResponseStream()))
        {
            return stream.ReadToEnd();
        }
    }


    /// <summary>
    /// (overload)
    /// Returns raw string of a call to the Twitch.tv API
    /// </summary>
    /// <param name="query">Query for API Call as string (HTTP request)</param>
    /// <returns></returns>
    public static string getRawData(string query)
    {
        var outboundRequest = (HttpWebRequest)WebRequest.Create(query);
        outboundRequest.Headers["Client-ID"] = Properties.TwitchAPISettings.Default.api_clientID; // and agagin...
        var inboundResponse = (HttpWebResponse)outboundRequest.GetResponse();

        saveRequest(query);
        using (StreamReader stream = new StreamReader(inboundResponse.GetResponseStream()))
        {
            return stream.ReadToEnd();
        }

    }

    /// <summary>
    /// Saves string of the last HTTP request made to the Twitch.tv API
    /// Used for Callbacks/Rollbacks
    /// </summary>
    /// <param name="query">HTTP request string</param>
    private static void saveRequest(string query)
    {
        Properties.TwitchAPISettings.Default.api_lastQuery = query;
        Properties.TwitchAPISettings.Default.Save();
    }

    /// <summary>
    /// Returns string of the last known HTTP request made to the Twitch.tv API
    /// </summary>
    /// <returns></returns>
    private static string getRequest()
    {
        return Properties.TwitchAPISettings.Default.api_lastQuery;
    }

Ok that’s a lot right? Now how do I use it.

Pretty simple actually. Everything is static and there is a reason for it. You do NOT need to create a new instance of the class to use the helpers contained within. So making a call could be as simple as this.

var root = TwitchAPIWrapper.rootserialize<Followers>("string query to the api here"); 

And that will pull populate a List<> full of follower related data at the root level (top). To do this you need to create public classes that json can tap into and populate based on that. Fortunately there are websites out there to help you achieve this.

http://jsonutils.com/ is a good one. Just throw the example data from twitch’s api pages and it’ll ouput a class for you to use with this function. Put the root of what you want to parse (followers, users) and let it do its thing. Just make sure you have the public class for json to use.

What you do with the code from here is up to you guys.

I hope this ends up helping somebody. If you need something explained, feel free to reply and I’ll do so.

Later :smile:

(there is exception handling you can place in there for not found, bad gateways etc, but i’ll let you figure that out, can’t make it too easy ;))

2 Likes

Thanks for the helpful post. I know there have to be people out there like me who aren’t “programmers” but can learn a lot from a working example and accomplish a more complex task with it.

Liked.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.