Tag Archives: HttpWebRequest

Playing with REST !

REST Services

àREST stands for Representational State Transfer, means that each unique URL is a representation of some object.

-to get the contents of that object use an HTTP GET,

-to delete you then might use a POST, PUT, or DELETE to modify the object.

àUnlike SOAP, REST is not a standard; it is just an architectural style.

àREST uses HTTP for all four CRUD (Create/Read/Update/Delete) operations.

àMuch like Web Services, a REST service is:

* Platform-independent (you don’t care if the server is Unix, the client is a Mac, or anything else),

* Language-independent (C# can talk to Java, etc.)

eg:

-The famous Twitter API is all REST.

Yahoo! offer most of their services using REST including Search API, Maps, Photos.

Flickr,

-Amazon.com offer several REST services, e.g., for their S3 storage solution

Atom is a RESTful alternative to RSS.

Like the following URL sends a REST request to Yahoo!’s web-search service:

http://search.yahooapis.com/WebSearchService/V1/webSearch?appid=YahooDemo&query=rest.

Click it, and observe the XML results, ready to be used directly.

This REST request includes two parameters:

appid“, used by Yahoo! to specify your application, and

query“, which is the actual search query.

REST vs SOAP

Yahoo’s web services are using REST and google using SOAP for their web services.

REST is Lightweight than SOAP because it does not requires lot of xml markup.

WCF 3.5 provides explicit support for RESTful communication using a new binding named WebHttpBinding.

The below code shows how to expose a RESTful service

[ServiceContract]

interface IStock

{

[OperationContract]

[WebGet(UriTemplate:=”/Stock/{StockId}”)]

int GetStock(string StockId);

}

By adding the WebGetAttribute, we can define a service as REST based service that can be accessible using HTTP GET operation, like GetStock from Stock.

We can use REST style to get order as shown in the below URL with Stock

http://localhost/stock.svc/Stock/100234

How to consume REST services

There are different ways to consume the REST services as per requirements, below I am mentioning some:

1) Here I am actually reading the Xml from REST service and writing to the file.  WebClient() is defined in System.Net
WebClient() objWebClient = new WebCleint();
objWebClient.Credentials = new NetworkCredential(uid, pwd, domain);
XmlTextReader objXmlTextReader = new XmlTextReader(objWebClient.OpenRead(path));
string objXml = string.Empty;

while(objXmlTextReader.Read())
{
   objXml = objXmlTextReader.ReadOuterXml;
}

string filePath = serverPath + “\” + Date.UtcNow.Year.Tostring();

if(File.Exists(filePath))
{  
   StreamWriter wr;
   File.Delete(filePath);
   wr = File.CreateText(filePath)
   wr.WriteLine(objXml)
   wr.Close();        
}
else
{
   StreamWriter wr;
   wr = File.CreateText(filePath)
   wr.WriteLine(objXml)
   wr.Close();
}

2) To query a REST service, like the one I mentioned above, we can use LINQ’s XML functionality.  The XElement class (declared in System.Linq.XML) provides a Load method that can retrieve an XML data from a url with GET  method:

XElement rootXml = XElement.Load(“http://search.yahooapis.com/WebSearchService/V1/webSearch?appid=YahooDemo&query=rest”);

var SearchResult = from R in rootXml.Elements()

select new { Topic = (string)R.Element(“Title”),

Detail = (string)R.Element(“Summary”),

Link = (string)R.Element(“Url”) };

foreach (var x in SearchResult)

Console.WriteLine(“{0}  {1}”, x.Topic, x.Detail, x.Link);

Console.ReadKey();

Using POST method is a bit more complex. First we have to obtain a channel by which we may POST the information. Then we have to create an instance of data entity in XML format. Finally we have to POST data through the channel.

To get access to REST service we use a HttpWebRequest since it lets use the POST method and let us specify the type of information we are posting.

HttpWebRequest channel = (HttpWebRequest)WebRequest.Create(“http://ws.geonames.org/countryInfo”);

channel.Method = “POST”;

channel.ContentType = “text/xml”;

HttpWebRequest class provides a stream to which we can write information :

StreamWriter sw = new StreamWriter(channel.GetRequestStream());

Then we can create a concerete entity to post:

XElement country = new XElement(“country” ,

new XElement(“countryCode”, “AUS”),

new XElement(“countryName” , “Australia”),

….

);

Finally we just need to save this XElement object to the stream we obtained from HttpWebRequest:

country.Save(sw);

References:

http://aspguy.wordpress.com/2008/10/10/dealing-with-rest-web-services/

http://developer.yahoo.com/dotnet/howto-rest_cs.html

2 Comments

Filed under .Net, C#