1

I am trying to access the Snipcart API (Reference - https://docs.snipcart.com/api-reference/authentication). I have created an API key and followed the steps mentioned in the documentation.

I am trying to Convert a CURL request to C#. I chose to use HttpWebRequest. I get 401 Unauthorized returned from the Server. I am not able to figure out what's wrong with my request.

Actual Curl Request: - curl -H "Accept: application/json" https://app.snipcart.com/api/orders -u {API_KEY}:

The following is the code that i tried converting the above curl request to

        string baseURL = "https://app.snipcart.com/api/orders";

        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(baseURL);
        req.AllowAutoRedirect = true;
        req.ContentType = "application/json";
        req.Accept = "application/json";
        req.Method = "GET";
        req.Headers.Add("API_Key", "MY_API_KEY_VALUE_COMES_HERE");

        string jsonResponse = null;
        using (WebResponse resp = req.GetResponse())
        {
            if (req.HaveResponse && resp != null)
            {
                using (var reader = new StreamReader(resp.GetResponseStream()))
                {
                    jsonResponse = reader.ReadToEnd();
                }
            }
        }
        Console.Write(jsonResponse);

2 Answers2

1

The API reference from Snipcart says you need Basic HTTP Authentication.

When I have a look at your code, I think you should change this line

req.Headers.Add("API_Key", "MY_API_KEY_VALUE_COMES_HERE");

to

req.Credentials = new NetworkCredential("API_Key", "MY_API_KEY_VALUE_COMES_HERE");

A kind of the same issue is described in this topic, you can take it as reference.

If it's not solving the issue, you could have a closer look at the curl API parameters manual, and then translate it to C# code.

curl -H "Accept: application/json" \
  https://app.snipcart.com/api/orders \
  -u {API_KEY}:
Jordy
  • 661
  • 7
  • 26
1

You need to send the header as a basic auth header instead of "API_Key" Try something like this.

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(baseURL);
req.AllowAutoRedirect = true;
req.ContentType = "application/json";
req.Accept = "application/json";
req.Method = "GET";
var basicAuthHeader = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes("MY_API_KEY_VALUE_COMES_HERE"));
req.Headers.Add("Authorization", "Basic " + basicAuthHeader);
DenverDev
  • 467
  • 3
  • 6