Simple API Integration in C# to Get IP Address

What is API:Application Programing Interface provides a medium of interaction between software components. Now-a-days API programing is one of the most important components of software development. Know more about API

API is something like URL that provides some intended data to the user. Let me explain it with some real world example.

Consider you have an account in Facebook and you want to access your friend list, status, photos through codding. Here Facebook is a total different entity which has no relation with your code (application), neither you can access Facebook’s code nor its database. So how can you access those data in your FB account via your application?

Here comes the role of API, Facebook provides an interface (URL/Graph API) that gives you all the intended details of your account, those can be used in any application. So your work is just to call the API provides by the client (here Facebook) and to use the response in your application. That’s it.

In this article I will show you a simple API call process in C# to get the IP address of the device, where your application is being opened.

Here is the sample project you can download it and check.

API-Download

  Download Source Code Here

 

Behind the Scene:

The main aim of an API is to return some desired information to the user so that those can be used across any application. There are many ways in which the API gives the response to the user.Mostly an API gives response in two formats

  • XML format
  • JSON format

(Here I will show you a sample API call to get IP address usingsmart-ip.net API)

A sample example of XML response.

     <?xml version="1.0" encoding="UTF-8"?>
    <geoip>
        <source>smart-ip.net</source>
        <host>193.178.146.17</host>
        <lang>en</lang>
        <countryName>Ukraine</countryName>
        <countryCode>UA</countryCode>
        <city>Kiev</city>
        <region>Kyyivs'ka Oblast'</region>
        <latitude>50.4333</latitude>
        <longitude>30.5167</longitude>
        <timezone>Europe/Kiev</timezone>
    </geoip>

A sample example of JSON response

         {
"source":"smart-ip.net"
"host":"193.178.146.17",
"lang":"en",
"countryName":"Ukraine",
"countryCode":"UA",
"city":"Kiev",
"region":"Kyyivs'ka Oblast'",
"latitude":50.4333,
"longitude":30.5167,
"timezone":"Europe/Kiev"
    }

In this example we will consider the JSON formatted response from the API. So let’s start our implementation. Our API to get the IP details ishttp://smart-ip.net/geoip-json?callback=?. You can find the response like below if you click on the above link.

    ?({"source":"smart-ip.net","host":"111.93.167.67","lang":"en","countryName":"India","countryCode":"IN","city":"Calcutta",
    "region":"West Bengal","latitude":"22.5697","longitude":"88.3697","timezone":"Asia\/Calcutta"});

You can find out your IP address in the above JSON response from the API along with your location, time zone etc. Now let’s do codding to implement this in c#. 

First create a class with the data members those you are expecting from the API response.

    public class ApiClass
    {

        public string host { get; set; }
        public string countryName { get; set; }
        public string city { get; set; }
    }

Here is the method to get the json response and to de-serialize it.

        protected void CallAPI()
        {
            // Createa request to call the dropbox api.
            WebRequest request = WebRequest.Create(new Uri("http://smart-ip.net/geoip-json?callback=?"));
            request.Method = "GET";
            request.ContentType = "application/json";

            // Get the response.
            WebResponse response = request.GetResponse();

            // Read the response.
            string apiResponse = new StreamReader(response.GetResponseStream()).ReadToEnd();
            apiResponse = apiResponse.Replace("?(", "").Replace(");", "");

            // Deserialize the json object.
            ApiClass apiObj = new JavaScriptSerializer().Deserialize<ApiClass>(apiResponse);

            // Set the label text.
            lblIP.Text = apiObj.host;
            lblCity.Text = apiObj.city;
            lblCountry.Text = apiObj.countryName;
        }

In the above method I am creating a WebRequest object with the above API and mentioning the method and contentType.Then get the response from the web request by calling GetResponse() method. Finally hold the response in a string and deserialize it to get the desired data.

 

That’s it you have just learned how to call an API in C#. Download the sample source code from the abovedownload link to see a live demo.

 

Happy Coding…

Written By: Tapan Kumar Khatua, Software Engineer, Mindfire Solutions

 

Advertisements

Posted on April 24, 2014, in ASP.Net, C# and tagged , , , , , , , , , , , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: