Dot Net For All

How to create a GET request from C# client

Hello, In this article I will show how we can make a web api GET request from C# code. This can be used as a quick reference if you are making a web api calls from your code. This is a step by step guide.

First let see the API which I will be calling. If you want to know how to create API with GET request, you can refer this article.

Below is the code of my web api class

    public class HomeController : ApiController
    {
        private static IList<Person> personList = GetPersonList();
        private static IList<Person> GetPersonList()
        {
            return new List<Person>() {
                new Person() { FirstName = "Vikram", LastName = "Chaudhary" },
                new Person() { FirstName = "Amit", LastName = "Kumar" },
                new Person() { FirstName = "Anoop", LastName = "Singh" } };
        }
        [Route("api/Home/Get")]
        [HttpGet]
        public HttpResponseMessage Get()
        {
            return Request.CreateResponse<string>(HttpStatusCode.OK, "Vikram");
        }
        [Route("api/Home/GetAllPerson")]
        [HttpGet]
        public HttpResponseMessage GetAllPerson()
        {
            return Request.CreateResponse<IList<Person>>(HttpStatusCode.OK, personList);
        }
        [Route("api/Home/GetLastName/{firstName}")]
        [HttpGet]
        public HttpResponseMessage GetLastName(string firstName)
        {
            if (personList.Where(item => item.FirstName.ToLower() == firstName).Count() > 0)
            {
                return Request.CreateResponse<Person>(HttpStatusCode.OK, personList.Where(item => item.FirstName.ToLower() == firstName).First());
            } else
            {
                return Request.CreateResponse<string>(HttpStatusCode.NotFound, "Person Not Found");
            }
        }
    }

As you can see in the above code I have to api calls(methods). One with parameter and one without parameter. And I will run the application on my local system.

I can access the above API by using the URL “localhost:59171/api/home/Get” or “localhost:59171/api/home/GetAllPerson”. The url can be different on your machine.

Now create a console application to access the api though HTTPClient in C#.

The HTTPCleint class is present under the System.Net.Http namespace. You need to add reference of the same namespace in your client.

In case if you are not able to find the above namespace you need to explicitly add the reference to the project and add the namespace as shown in the below code.

Now we can use the below code to call the first method i.e. Get which just returns a single name.

var response = client.GetAsync("http://localhost:52854/api/Home/GetAllPerson");
if (response.Result.StatusCode == System.Net.HttpStatusCode.OK)
{
    var result = response.Result.Content.ReadAsStringAsync();
                     Console.WriteLine(result.Result);
}
           

We will get the one name printed on the console. But suppose if you want to get all the persons present in the list. And we want to recreate the list at the client side. We can use Newtonsoft json convertor as shown in the code below.

The below code shows how we can convert a json string to .NET type  using json convertor

 using (HttpClient client = new HttpClient())
            {
                var response = client.GetAsync("http://localhost:52854/api/Home/GetAllPerson");
                if (response.Result.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    var result = response.Result.Content.ReadAsStringAsync();
                    IList<Person> personList =  (IList<Person>)Newtonsoft.Json.JsonConvert.DeserializeObject(result.Result, typeof(IList<Person>));
                }
            }

The person type should be known to the client.

Now  in the service there is a method which takes a string as parameter. If we want to call that para metered method of the web api we should use the below code.

 using (HttpClient client = new HttpClient())
            {
                var response = client.GetAsync("http://localhost:52854/api/Home/GetLastName/vikram1");
                if (response.Result.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    var result = response.Result.Content.ReadAsStringAsync();
                    Person personList =  (Person)Newtonsoft.Json.JsonConvert.DeserializeObject(result.Result, typeof(Person));
                }
                else
                {
                    var result = response.Result.Content.ReadAsStringAsync();
                    Console.WriteLine(result.Result);
                }
            }

As we can see in the web api code, there are very good chances that the person is not present in the list. In that case we are simply returning a string in the response.

And in the client side we need to handle this scenario as well which I have done in my above code.

In this article I have showed how we can issue get request from C# client code for various scenarios.

Top career enhancing courses you can't miss

My Learning Resource

Excel your system design interview