Wednesday, December 11, 2013

Using the Shopify API from .NET

If you're looking for a way to talk to Shopify from .NET (either C# or VB.NET), you'll probably come across this "lightweight" .NET client.

Word of warning: it's 10 MB, and pretty hard-core.

If you're writing a private app (as opposed to a public one), things are much simpler; you don't need all the OAuth stuff for starters. After a bit of trial and error, I got this to work:

public string GetCustomers()
{
const string url = "https://your-store.myshopify.com/admin/customers.json";
var req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "GET";
req.ContentType = "application/json";
req.Credentials = GetCredential(url);
req.PreAuthenticate = true;
using (var resp = (HttpWebResponse)req.GetResponse())
{
if (resp.StatusCode != HttpStatusCode.OK)
{
string message = String.Format("Call failed. Received HTTP {0}", resp.StatusCode);
throw new ApplicationException(message);
}
var sr = new StreamReader(resp.GetResponseStream());
return sr.ReadToEnd();
}
}
private static CredentialCache GetCredential(string url)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
var credentialCache = new CredentialCache();
credentialCache.Add(new Uri(url), "Basic", new NetworkCredential("your-api-key", "your-password"));
return credentialCache;
}



To generate an API key and password, go to http://your-store.myshopify.com/admin/apps, and click "Create a private API key" at the bottom.