Skip to content

Instantly share code, notes, and snippets.

@tgaraptor
Last active February 7, 2017 13:30
Show Gist options
  • Save tgaraptor/0fa5debdefe0fb67e25cb63601832da0 to your computer and use it in GitHub Desktop.
Save tgaraptor/0fa5debdefe0fb67e25cb63601832da0 to your computer and use it in GitHub Desktop.
Async, non-blocking request to the Raptor API with timeout and fallback
using System;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
namespace RaptorCaller
{
public class Program
{
public static void Main(string[] args)
{
CallRaptor().Wait();
}
public static async Task CallRaptor()
{
var customerId = "[YourCustomerIdHere]"; //A number string, which can be found in the Raptor controlpanel
var apiMethodName = "[Your apimethod name here]"; //For instance: "GetOverAllTopVisits"
var apiKey = "[Your api key here]"; //A guid, which can be found in the Raptor controlpanel
var numberOfRecommendations = 10; //Can be set to a number from 1-100
var timeout = TimeSpan.FromSeconds(1.5); //first call to c# httpclient can take 1+ seconds. next calls should be <400ms depending on network latency
try
{
var json = await RaptorCaller.GetJson(customerId, apiMethodName, apiKey, timeout,
numberOfRecommendations);
//Using Json.NET to parse the json result. Can be installed using nuget.
var jsonArray = JArray.Parse(json);
var productIds = jsonArray
.Select(item => item["ProductID"])
.ToList(); //NB: Refer to the raptor controlpanel, for exact parameter names
}
catch (OperationCanceledException cancelled)
{
//timeout
//Log
//Return fallback
}
catch (HttpRequestException exception)
{
//?? exception
//Log
//Return fallback
}
}
}
public static class RaptorCaller
{
private static readonly HttpClient HttpClient = new HttpClient();
/// <summary>
/// Returns JSON array from RaptorApi. Ie. [{"ProductId":"aaa"},{"ProductId":"bbb"},{"ProductId":"ccc"}]
/// </summary>
/// <param name="customerId">Found in controlpanel</param>
/// <param name="apiMethodName">Found in controlpanel. Ie.GetOverAllTopVisits </param>
/// <param name="apiKey">Found in controlpanel. Ie 786A5152-9B08-4577-BBBA-5EC8F65AB3EF</param>
/// <param name="timeout"></param>
/// <param name="numberOfRecommendations">expected number to receive. default= 10</param>
/// <returns>JArray</returns>
/// <exception cref="OperationCanceledException"></exception>
/// <exception cref="HttpRequestException"></exception>
public static async Task<string> GetJson(string customerId, string apiMethodName, string apiKey, TimeSpan timeout, int numberOfRecommendations = 10)
{
var url = new Uri($"https://api.raptorsmartadvisor.com/v1/{customerId}/{apiMethodName}/{numberOfRecommendations}/{apiKey}?");
HttpClient.DefaultRequestHeaders.Accept.Clear();
HttpClient.DefaultRequestHeaders.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("appplication/json"));
var cancellationTokenSource = new CancellationTokenSource(timeout);
var responseMessage = await HttpClient.GetAsync(url, cancellationTokenSource.Token);
responseMessage.EnsureSuccessStatusCode();
return await responseMessage.Content.ReadAsStringAsync();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment