Last active
December 17, 2015 22:29
-
-
Save bradygaster-zz/5682105 to your computer and use it in GitHub Desktop.
A generic class that can call REST services and parse their JSON output, or process the deserialized version of the JSON output.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace GenericRestTools | |
{ | |
using Newtonsoft.Json; | |
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Net.Http; | |
using System.Text; | |
using System.Threading.Tasks; | |
public class GenericJsonApiClient | |
{ | |
public async Task<TExpected> Get<TRequest, TExpected>(TRequest request, | |
Func<TRequest, Uri> uriBuilder) | |
{ | |
var uri = uriBuilder(request); | |
var client = new HttpClient(); | |
var msg = new HttpRequestMessage(HttpMethod.Get, uri); | |
var response = await client.SendAsync(msg); | |
var content = await response.Content.ReadAsStringAsync(); | |
return JsonConvert.DeserializeObject<TExpected>(content); | |
} | |
public async Task<GenericJsonApiClient> Get<TRequest, TExpected>(TRequest request, | |
Func<TRequest, Uri> uriBuilder, | |
Action<TExpected> processor = null) | |
{ | |
var result = await Get<TRequest, TExpected>(request, uriBuilder); | |
if (processor != null) | |
processor(result); | |
return this; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var request = new CustomerRequest | |
{ | |
Id = 42 | |
}; | |
await new GenericJsonApiClient().Get<CustomerRequest, List<CustomerResponse>>(request, | |
(query) => | |
{ | |
return new Uri(string.Format("http://mysite.com/api/customer/{0}", | |
query.Id) | |
); | |
}, | |
(customers) => | |
{ | |
customers.ForEach(r => | |
{ | |
Console.WriteLine("{0} {1}, {2}", | |
r.FirstName, | |
r.LastName); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment