51

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?

3
  • 1
    I'm not seeing the issue here. The fact that your client itself is a Web API service makes no difference in how you can call a Web API service.
    – user247702
    Oct 18, 2013 at 11:37
  • Please accept the answer instead of commenting with thanks, this way this question will no longer be open
    – OnTheFly
    Oct 18, 2013 at 12:46
  • I tried with RestSharp, its a simpler one. You can get full source code: github.com/garora/somestuff/tree/master/ConsumeWebAPI Oct 5, 2014 at 10:57

3 Answers 3

93

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.

5
  • I have tried to consume service from A Console Application and am Successful. I am facing problem in consuming the same from Asp.Net WebApi. my queries are : 1. Where to write httpclient program in webApi project, since program should auto execute once in a day to update my DB? 2. Is it recommended to use nomysqldbs like mongo db or any other since my responce is JSON Objects? Oct 19, 2013 at 6:12
  • Why are you using another web api if you want to execute it once a day? You could use your console application and windows scheduled tasks, to execute it once a day. Your database choice totally depends on other requirements.
    – Nick N.
    Oct 19, 2013 at 12:59
  • I need to expose my DB to my clients through the WEB API which I am trying to implement. Its an intermediate service. Archietecture looks like.. WEB API(Third Party) <--> WEB API <--> client Oct 21, 2013 at 5:29
  • Why not a console application with scheduled tasks for calling the other Web API, and your own Web API to expose your DB
    – Nick N.
    Oct 25, 2013 at 7:25
  • wouldnt that create a CORs issue? Nov 24, 2018 at 3:54
9

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.

2
  • 1
    for me, this soln works after adding data.result(instead of data) in below line of code "var product = JsonConvert.DeserializeObject<Product>(data);" Oct 19, 2015 at 13:17
  • 1
    JsonConvert is located in newtonsoft.json package, get it from nuget package manger :)
    – AmiNadimi
    Nov 27, 2016 at 15:00
1
public class EmployeeApiController : ApiController
{
    private readonly IEmployee _employeeRepositary;

    public EmployeeApiController()
    {
        _employeeRepositary = new EmployeeRepositary();
    }

    public async Task<HttpResponseMessage> Create(EmployeeModel Employee)
    {
        var returnStatus = await _employeeRepositary.Create(Employee);
        return Request.CreateResponse(HttpStatusCode.OK, returnStatus);
    }
} 

Persistance

public async Task<ResponseStatusViewModel> Create(EmployeeModel Employee)
{    
    var responseStatusViewModel = new ResponseStatusViewModel();
    var connection = new SqlConnection(EmployeeConfig.EmployeeConnectionString);
                var command = new SqlCommand("usp_CreateEmployee", connection);
                command.CommandType = CommandType.StoredProcedure;
                var pEmployeeName = new SqlParameter("@EmployeeName", SqlDbType.VarChar, 50);
                pEmployeeName.Value = Employee.EmployeeName;
                command.Parameters.Add(pEmployeeName);


                try
                {
                    await connection.OpenAsync();
                    await command.ExecuteNonQueryAsync();

                    command.Dispose();
                    connection.Dispose();

                }
                catch (Exception ex)
                {

                    throw ex;
                }
                return responseStatusViewModel;
            }

Repository

Task<ResponseStatusViewModel> Create(EmployeeModel Employee);

public class EmployeeConfig
{
    public static string EmployeeConnectionString;
    private const string EmployeeConnectionStringKey = "EmployeeConnectionString";
    public static void InitializeConfig()
    {
        EmployeeConnectionString = GetConnectionStringValue(EmployeeConnectionStringKey);
    }

    private static string GetConnectionStringValue(string connectionStringName)
    {
        return Convert.ToString(ConfigurationManager.ConnectionStrings[connectionStringName]);
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.