Consume Web API data using HttpClient
in c#
HttpClient
is a base class for sending HTTP requests and receiving HTTP responses from a
resource identified by a URI.
Following
code example get movies data in JSON format,
Web API code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Threading;
using System.Net.Http.Headers;
public class RestAPICall
{
private const string URL = "https://c4utest.com/api/movies/search";
private const string urlParameters = "?Title=Bahubali ";
public void DisplayMoviesFromRestAPI()
{
using (var client = new
HttpClient())
{
client.BaseAddress = new
Uri(URL);
// List data response.
HttpResponseMessage response =
client.GetAsync(urlParameters).Result;
// blocking call
if
(response.IsSuccessStatusCode)
{
// Parse the
response body.
var dataObjects =
response.Content.ReadAsStringAsync().Result;
//data objects
Movies deserializedProduct
= JsonConvert.DeserializeObject<Movies>(dataObjects);
JObject jsonval =
JObject.Parse(dataObjects);
if (deserializedProduct !=
null)
{
Console.WriteLine("Total movies : "+
deserializedProduct.total);
Console.WriteLine("Current page : " +
deserializedProduct.page);
Console.WriteLine("Total pages : " +
deserializedProduct.total_pages);
//first movie details
var firstMoviesDetails
= deserializedProduct.data.FirstOrDefault();
//Display first moview
details from collections
Console.WriteLine("First movie title : " +
firstMoviesDetails.Title);
Console.WriteLine("First movie release
year : " + firstMoviesDetails.Year);
Console.WriteLine("First movie code : " +
firstMoviesDetails.imdbID);
//display all movies
details
foreach (var
movieDetail in deserializedProduct.data)
{
Console.WriteLine("Movie title : " + movieDetail.Title);
Console.WriteLine("Movie release year : " + movieDetail.Year);
Console.WriteLine("Movie
code : " + movieDetail.imdbID);
}
}
}
else
{
Console.WriteLine("{0}
({1})", (int)response.StatusCode, response.ReasonPhrase);
}
}
}
}
Movies class
public class Movies
{
public int page { get; set; }
public int per_page { get; set; }
public int total { get; set; }
public int total_pages { get; set; }
public List<MoviesData> data { get; set; }
}
MoviesData class
public class MoviesData
{
public string Title { get; set; }
public int Year { get; set; }
public string imdbID { get; set; }
}
The Abstract
Modifier
The abstract modifier indicates that
the thing being modified has a missing or incomplete implementation. The
abstract modifier can be used with classes, methods, properties, indexers, and
events.
The Virtual
Keyword
The virtual keyword is used to modify
a method, property, indexer, or event declaration and allow for it to be
overridden in a derived class.
The Override
Modifier
The override modifier is required to
extend or modify the abstract or virtual implementation of an inherited method,
property, indexer, or event.
Override Rules
- The overridden base method is a
virtual, abstract, or override method. In other words, the overridden base
method cannot be static or non-virtual.
- The overridden base method is not a
sealed method.
- The override method and the overridden
base method have the same return type and same signature.
- The override declaration and the
overridden base method have the same declared accessibility (i.e public, internal
etc).
- The override declaration does not
specify type-parameter-constraints-clauses. Instead the constraints are
inherited from the overridden base method.
Reference: https://docs.microsoft.com/
Code example
In following example override modifier
is used to implement the abstract and extend virtual implementation of an
inherited methods Print () and Display (), always it will call extended/ modified
members.
public abstract class OverrideParent
{
//Concreate implementation, child allowed to override
public virtual void Print()
{
Console.WriteLine("Parent virtual print");
}
//pure abstract member, child must override
public abstract void Display();
}
public class ChildOverride :OverrideParent
{
public override void Print()
{
Console.WriteLine("1st level print override");
}
public override void Display()
{
Console.WriteLine("1st level implementation");
}
}
public class NestedChildOverride: ChildOverride
{
public override void Print()
{
Console.WriteLine("2nd level print override");
}
public override void Display()
{
Console.WriteLine("2nd level override/implementation");
}
}
Client implementation
//How
it works?
class Program
{
static void
Main(string[] args)
{
OverrideParent ParentTypeChildImpn
= new ChildOverride();
ChildOverride ChildTypeChildImpn = new ChildOverride();
ChildOverride
ChildTypeNestedChldImpl = new NestedChildOverride();
NestedChildOverride
NestedChildTypeNestedImpl= new NestedChildOverride();
//parent
abstract type and child implementation
ParentTypeChildImpn.Print();
ParentTypeChildImpn.Display();
//child
type and child implementations
ChildTypeChildImpn.Print();
ChildTypeChildImpn.Display();
//Child
type and derived nested implementations
ChildTypeNestedChldImpl.Print();
ChildTypeNestedChldImpl.Display();
//Nested
child type and nested implementations
NestedChildTypeNestedImpl.Print();
NestedChildTypeNestedImpl.Display();
}
}
Output:
What is anonymous
method in C#?
A method without a name is called as
an anonymous method is, the delegate operator creates an anonymous method that
can be converted to a delegate type.
What is use of
anonymous methods in C#?
- You can use an anonymous method to
create an anonymous function with unnamed inline code.
- C# 2.0 introduced the concept of
anonymous methods to write unnamed inline statement blocks that can be executed
in a delegate invocation.
How to create and
use anonymous method?
An anonymous method behaves like a
regular method and allows us to write inline code in place of explicitly named
methods.
Code example
//declare delegate
delegate void displayFullName(string fname, string mName, string lName);
//instantiate delegate with anonymous method
displayFullName fullName = delegate (string fname, string mName, string lName) {
Console.WriteLine("Full name: " + fname + " " + mName + " " + lName);
};
//anonymous method with generic action delegate
Action<string, string, string> userFullName = delegate (string fname, string mName, string lName)
{
Console.WriteLine("User full name: " + fname + " " + mName + " " + lName);
};