Call Rest Api With C#

Call Rest Api With C#

by Omar Guerrero -
Number of replies: 0

This is an example in Console with C#  to how to call the api of moodle with only the class and reflection


using System;

using System.Collections.Generic;

using System.IO;

using System.Linq;

using System.Net;

using System.Text;

using System.Threading.Tasks;

using Newtonsoft.Json;

using System.Net.Http;

using System.Net.Http.Headers;

using System.Collections;


namespace TestApiMoodle

{

    class Program

    {

        static void Main(string[] args)

        {

            Course course = new Course();

            course.categoryid = 1;

            course.format = "topics";

            course.fullname = "curso de prueba de web service5";

            course.shortname = "prueba5";

            course.visible =1;

            CreateCourse(course);

        }


      


        public static void CreateCourse(Course course)

        {

             var request =WebRequest.Create("http://XXXXXX/webservice/rest/server.php");

            request.Credentials = CredentialCache.DefaultCredentials;

            ((HttpWebRequest)request).UserAgent = ".NET Framework Example Client";

            request.Method = "POST";

            request.ContentType = "application/x-www-form-urlencoded";

            CourseCall callObject = new CourseCall();

            callObject.courses = new List<Course>();

            callObject.courses.Add(course);

            byte[] byteArray = Encoding.UTF8.GetBytes(GetQueryString(callObject));

            request.ContentLength = byteArray.Length;

            Stream dataStream = request.GetRequestStream();

            dataStream.Write(byteArray, 0, byteArray.Length);

            dataStream.Close();

            using (var response = (HttpWebResponse)request.GetResponse())

            {

                var responseValue = string.Empty;

                if (response.StatusCode != HttpStatusCode.OK)

                {

                    var message = String.Format("Request failed. Received HTTP {0}", response.StatusCode);

                    throw new ApplicationException(message);

                }

                using (var responseStream = response.GetResponseStream())

                {

                    if (responseStream != null)

                        using (var reader = new StreamReader(responseStream))

                        {

                            responseValue = reader.ReadToEnd();

                        }

                }

                Console.WriteLine( responseValue);

            }

        }

        public static string GetQueryString(object obj)

        {

            List<string> properties = new List<string>();

            string OpenSquareBracket = System.Web.HttpUtility.UrlEncode("[");

            string CloseSquareBracket = System.Web.HttpUtility.UrlEncode("]");

            foreach (var p in obj.GetType().GetProperties().Where(x=>x.GetValue(obj,null) !=null))

            {

                if (p.PropertyType.IsGenericType)

                {

                    var subp = p.GetValue(obj);

                    List<string> ListObject = new List<string>();

                    int i = 0;

                  

                    foreach (var listitem in subp as IEnumerable)

                    {

                        foreach (var propertyItem in listitem.GetType().GetProperties())

                        {

                            ListObject.Add(string.Concat(p.Name ,

                                OpenSquareBracket, i.ToString(),CloseSquareBracket,

                                OpenSquareBracket, propertyItem.Name ,CloseSquareBracket, "=", System.Web.HttpUtility.UrlEncode(propertyItem.GetValue(listitem, null).ToString())));

                        }

                        i++;

                    }

                    properties.Add(string.Join("&", ListObject));

                }

                else

                {

                    properties.Add(string.Concat(p.Name, "=", System.Web.HttpUtility.UrlEncode(p.GetValue(obj, null).ToString())));

                }

            }

            return String.Join("&", properties.ToArray());

        }


        

        public class Course

        {

            public string fullname { get; set; }

            public string shortname { get; set; }

            public int categoryid { get; set; }

            public string format { get; set; }

            public int visible { get; set; }

            public string groupmode { get; set; }

            public string groupmodeforce { get; set; }

            public  Course()

            {

                groupmode = "1";

                groupmodeforce = "0";

            }

            

        }

        

        public class CourseCall

        {

           

            public string wstoken { get; set; }

            public string wsfunction { get; set; }

            public string moodlewsrestformat { get; set; }

            public List<Course> courses { get; set; }

           

            public   CourseCall()

            {

                moodlewsrestformat = "json";

                wsfunction = "core_course_create_courses";

                wstoken = "XXXXXXX";

            }

        }


    }

}


Average of ratings: -