Search code examples
c#webrequestrest

Using Permanent Token in API HTTP Call


I'm writing a C# desktop app that will make some API calls to retrieve some data in JSON in which I'll parse. I'm using Deputy's API (https://www.deputy.com/api-doc/API/Getting_Started) and I'm having trouble getting it to work with a permanent token (I followed their steps and generated a token, so I have one). In the past I usually just do a HttpWebRequest and pass it the api url and it works fine. But in the past if there was an api key I would do something like &api_key=api_key_here or if I had an authorization key it would be something like &Authorization=put_token_here.

So I'm just trying to get Roster working for example:/api/v1/supervise/roster/ (see https://www.deputy.com/api-doc/API/Roster_Management_Calls).

So my code looks something like this:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    try
    {
        HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create(
            "https://mysite.na.deputy.com/api/v1/supervise/roster&Authorization=my_permanent_token_here"
            );
        httpWReq.Method = "GET";
        HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();
        string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

        this.Invoke((MethodInvoker)delegate
        {
            richTextBox1.AppendText(responseString + Environment.NewLine);
        });
    }
    catch (Exception ex)
    {
        this.Invoke((MethodInvoker)delegate
        {
            richTextBox1.AppendText(ex.ToString());
        });
    }
}

But I'm getting the following:

{"error":{"code":403,"message":"No authorization given"}}

I think it has to be the syntax on my permanent token, but I've tried api_key= and token= and authorization=. Can anyone help me out?


Solution

  • You need to pass the token as a line in the request header in the following format:

    Authorization: OAuth YOURTOKEN
    

    Use the following code:

    string permanentAccessToken = "123456";
    
    WebRequest request = WebRequest.Create("http://blabla");
    request.Headers.Add("Authorization", "OAuth " + permanentAccessToken);