C# calling REST API's using complext types (objects)

So we have been rolling out Web API's to expose functions to other systems.  This is great, but it isn't like SOAP where you have a WSDL, import it and you can code against it.  You have to do more work than that.  We don't want to be completely blind and just pass xml / json around and let each side figure out what the type looks like, so we should compile our main types to classes and share them between assemblies.  Then when we request or post a product, we can easily just have it as its native type.  Here is how.

If I wanted to post a product to a function, I would do it like this.

var client = new RestClient(Config.GetString("QASpecWebClient", true));
                var request = new RestRequest(Config.GetString("QASpecWebFunction", true), Method.POST);
                request.RequestFormat = DataFormat.Json;
                var resp = client.Execute(request);

Notice how we just AddBody the product.  It is a complex type that the service in question uses as well.  Luckily RestSharp takes care of converting it to json to get it there.

If we want to request a product from a function, I would do it like this.

var client = new RestClient("http://localhost:62991/");
var request = new RestRequest("api/productapi/"+id.ToString());
request.RequestFormat = DataFormat.Json;
var resp = client.Execute(request);
var returner = JsonConvert.DeserializeObject<IProduct>(resp.Content);
return returner;

Notice how we just do the same client request setup, don't add a body, and then use the deserialze function template to our type and boom, we have a complex type with no messy parsing.  Enjoy!


Oh, don't forget to include Newtonsoft.Json and RestSharp! 

Add comment