Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GDax API GET request always returns Error 400

Tags:

c#

api

I'm trying to get the order book from GDAX (link to documentation of the call) but when doing it from the c# executable I always get Error 400 - Bad request.

When taking the actual URL and pasting it into my browser, it works fine.

String URL = "https://api.gdax.com/products/BTC-USD/book?level=2";
WebRequest request = WebRequest.Create(URL);
WebResponse response = request.GetResponse();
like image 243
Nicksta Avatar asked Jan 31 '23 02:01

Nicksta


1 Answers

The actual issue with your API call is , the API is expecting a user-agent string while making the request: Below is the code in working condition:

        try
        {

            String URL = "http://api.gdax.com/products/BTC-USD/book?level=2";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);                
            request.UserAgent = ".NET Framework Test Client";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            var encoding = ASCIIEncoding.ASCII;
            using (var reader = new System.IO.StreamReader(response.GetResponseStream(), encoding))
            {
                string responseText = reader.ReadToEnd();
            }

        }
        catch(WebException ex)
        {
            HttpWebResponse xyz = ex.Response as HttpWebResponse;
            var encoding = ASCIIEncoding.ASCII;
            using (var reader = new System.IO.StreamReader(xyz.GetResponseStream(), encoding))
            {
                string responseText = reader.ReadToEnd();
            }
        }

Basically ProtocolError indicates that you have received the response but there is an error related to protocol, which you can observe, when you read the response content from exception. I have added catch to handle the exception and read ex.Response (which is HttpWebResponse) and could see that the API is asking for user-agent to be suppllied while making the call. I got to see the error as "{"message":"User-Agent header is required."}"

You can ignore the code inside the exception block, I used it only to see what is the actual response message, which contains actual error details

Note: I have boxed WebRequest to HttpWebRequest to have additional http protocol related properties and most importantly "UserAgent" property which is not available with the WebRequest class.

like image 81
Sujith Avatar answered Feb 02 '23 11:02

Sujith