Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to consume a webApi from asp.net Web API to store result in database?

I'm wondering how to consume a WEBAPI from another ASP.Net Web API to store the response in a database. I know how to consume a WEBAPI from clients like javascript,console application etc.

But the requirement is to pull the data from third party API by my WEBAPI & store the result in a database so that using my WEBAPI my clients request me for data.

Is it possible to do this with an Asp.Net Web API?

like image 878
Karthik Dheeraj Avatar asked Oct 18 '13 11:10

Karthik Dheeraj


People also ask

Can we return file result from API?

Let's assume, we have a requirement to send a file based on the file type provided to the service request. For example, when we send the file type as PDF, service will return PDF file if we send Doc, service will return Word document. (I have taken this sample to cover all types of files).


2 Answers

In this tutorial is explained how to consume a web api with C#, in this example a console application is used, but you can also use another web api to consume of course.

http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client

You should have a look at the HttpClient

HttpClient client = new HttpClient(); client.BaseAddress = new Uri("http://localhost/yourwebapi"); 

Make sure your requests ask for the response in JSON using the Accept header like this:

client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); 

Now comes the part that differs from the tutorial, make sure you have the same objects as the other WEB API, if not, then you have to map the objects to your own objects. ASP.NET will convert the JSON you receive to the object you want it to be.

HttpResponseMessage response = client.GetAsync("api/yourcustomobjects").Result; if (response.IsSuccessStatusCode) {     var yourcustomobjects = response.Content.ReadAsAsync<IEnumerable<YourCustomObject>>().Result;     foreach (var x in yourcustomobjects)     {         //Call your store method and pass in your own object         SaveCustomObjectToDB(x);     } } else {     //Something has gone wrong, handle it here } 

please note that I use .Result for the case of the example. You should consider using the async await pattern here.

like image 70
Nick N. Avatar answered Oct 02 '22 17:10

Nick N.


For some unexplained reason this solution doesn't work for me (maybe some incompatibility of types), so I came up with a solution for myself:

HttpResponseMessage response = await client.GetAsync("api/yourcustomobjects"); if (response.IsSuccessStatusCode) {     var data = await response.Content.ReadAsStringAsync();     var product = JsonConvert.DeserializeObject<Product>(data); } 

This way my content is parsed into a JSON string and then I convert it to my object.

like image 43
MalachiteBR Avatar answered Oct 02 '22 19:10

MalachiteBR