Resolved Read data from API response

AlexJames

Well-known member
Joined
Mar 20, 2020
Messages
65
Programming Experience
10+
Hi All

I'm currently consuming a REST api and i need some guidance on reading the response data. My experience with reading this type of data is very minimal and i'm trying to find the best way to do it.

below is the code for getting the API data.

C#:
 public string ModitarWebRequestCall()
        {
            string apiUrl = "https://api.moditar.com/Document/GetContent";
            string username = "JohnDoe";
            string password = "Password123";
            string collection = "ea85fbf3-5858-4348-bcab-08a8f39ad30c";
            string markasread = "False";

            var request = (HttpWebRequest)WebRequest.Create(apiUrl);
            request.Method = "GET";
            request.Accept = "application/xml";

            request.Headers.Add("username", username);
            request.Headers.Add("password", password);
            request.Headers.Add("collection", collection);
            request.Headers.Add("Markasread", markasread);

            string content = string.Empty;
            try
            {
                using (var response = (HttpWebResponse)request.GetResponse())
                {
                    using (var stream = response.GetResponseStream())
                    {
                        using (var sr = new StreamReader(stream))
                        {
                            content = sr.ReadToEnd();
                            sr.Close();
                            Console.WriteLine("Data received from Moditar");
                        }
                    }
                }
                return content;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return null;
            }
        }

I'm using the code below to call the above method and this is where I need to process the data.

C#:
        public void ProcessDatafromModitarApi()
        {
            var getData = new ModitarApiConnection();
            getData.ModitarWebRequestCall();
        }

What is the best way to read this data ? there are options for json, xml readers, leave it as text etc. so many choices. Any guidance on this would be greatly appreciated.
 
No worries at all Sheepings, I really appreciate you guys taking the time to help me with this and learn.
Don't be silly, that's what we are all here for. Our job is to provide solutions. Sorry I'm not throwing source code at you to help you with this. My hands are tied today, and I've only time to throw advice out there atm.

Skydiver is putting you on the right track, and also take note of post 30 where he points out one of the lines in your code which I also called redundant.

If you are going to use any readers, pass the reader in directly for deserializing, instead of going from stream to string. Etc as I mentioned one page back
 
Thanks guys, I'm back and hopefully with a clearer head. Just to clarify based on the last two posts, it would be better for me to deserialise the stream and then pass that object back to my calling method, instead of stream to string and then too object.
 
Looks like i'm finally making some progress, managed to deserialze the stream data, next step is to try and read the XML.

C#:
 public class ModitarApiConnection
    {
        public class Document
        {
            
        }
        public Object ModitarWebRequestCall()
        {
            string apiUrl = "https://api.moditar.com/Document/GetContent";
            string username = "testing123";
            string password = "password1213";
            string collection = "ea85fbf3-5858-4348-bcab-08a8f39ad30c";
            string markasread = "False";

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(apiUrl);
            request.Method = "GET";
            request.Accept = "application/xml";

            request.Headers.Add("username", username);
            request.Headers.Add("password", password);
            request.Headers.Add("collection", collection);
            request.Headers.Add("Markasread", markasread);

            try
            {
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    using (Stream stream = response.GetResponseStream())
                    {
                        using (StreamReader sr = new StreamReader(stream))
                        {
                            var mySerializer = new XmlSerializer(typeof(Document));
                            var myXmlObject = (Document)mySerializer.Deserialize(stream);
                            return myXmlObject;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return null;
            }
        }
    }

Please let me know if you guys can spot anything wrong or something i can do better in the above code, trying to learn as much as i can as i go.
 
Delete line 30. You are not using the StreamReader anyway.

You really should put those magic strings on lines 9-12 (or 9-13 ?) into your app.config or web.config. Embedding passwords and other secrets in code is typically a bad idea. For a toy application or prototoype, but you indicated in this thread and another thread that this is production work for hire so you may want to make your code more production ready.

Doing Pokemon exception handling on line 39 is usually a bad idea unless this is a toy application. You previously indicated in this thread and another thread that this is production work for hire so you may want to make your code more production ready.

Have you considered what happens if the password or username is not in the ASCII range?

Have you considered using the HttpClient or WebClient classes instead?

Coding style things:

The new coding style recommendations for C# is to prefer using var instead of explicitly putting in the type if the type can be easily implied from the assignment.

Notice how lines 25-38 gets more and more deeply embedded and looks like an arrow. Some people call this an "arrow pattern" and consider it an anti-pattern because the deep nesting makes it harder to read the code. Prior to C# 8.0, the usual coding style would be to re-write it as:
C#:
try
{
    using (var response = (HttpWebResponse)request.GetResponse())
    using (var stream = response.GetResponseStream())
    {
        var mySerializer = new XmlSerializer(typeof(Document));
        var myXmlObject = (Document)mySerializer.Deserialize(stream);
        return myXmlObject;
    }
}
But if you have C# 8.0, this could be further re-written as:
C#:
try
{
    using var response = (HttpWebResponse)request.GetResponse();
    using var stream = response.GetResponseStream();
    var mySerializer = new XmlSerializer(typeof(Document));
    var myXmlObject = (Document)mySerializer.Deserialize(stream);
    return myXmlObject;
}
 
Hi Skydiver

Thank you for your reply and the great suggestions, the "magic strings" will be populated from fields in a database that will be setup in the main application, I just hard coded them in for testing purposes and the same with the error trapping and exceptions, i'll make those more robust once I have the XML figured out. I'm glad you mentioned the var keyword, I'm using Visual Studio 2019 and the latest C# and VS 2019 keeps suggesting that i use the implicit convention whenever i use var, so i thought that was the new norm (glad it isn't) lol, I way prefer var. The one thing I'm struggling with now is reading the returned object, i'm not 100% sure how to do that. Here is my caller method (still unchanged), i'm not sure what to iterate through to read the data.

C#:
    class ProcessXML
    {
        public void ProcessDatafromModitarApi()
        {
            var getData = new ModitarApiConnection();
            getData.ModitarWebRequestCall();
        }
    }

Thanks again Skydiver, I'm going to make those improvements to my code now.

Mod edit, no need to quote the person directly above you. Massive quote removed.
 
Last edited by a moderator:
Thank you so much for your help guys, I've managed to make some progress. I'm going to mark this thread resolved and will start a new one if I face any other problems.
 

Latest posts

Back
Top Bottom