1

I'm working on a new application where I need to use Clockify's API. When I make my test application for a proof of concept, I notice that I'm getting a 401 error as a response to using one of their base functions, get clients by work space. Am I missing something with the authentication? Is there a setting I need to allow on my profile? The error I'm getting is: System.Net.WebException: 'The remote server returned an error: (401) Unauthorized.' Thanks.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace Api
{
    public class ApiHelper
    {
        public static HttpClient ApiClient { get; set; } = new HttpClient();

        public static void InitializeClient(string username, string password)
        {
            ApiClient = new HttpClient();
            ApiClient.BaseAddress = new Uri("https://api.clockify.me/api/");
            ApiClient.DefaultRequestHeaders.Accept.Clear();
            ApiClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        }

        public static void GetClientsFromWorkspace(string workspace)
        {
            ApiClient.DefaultRequestHeaders.Add("X-Api-Key", "*********");
            var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://api.clockify.me/api/workspaces/" + workspace + "/clients");
            httpWebRequest.ContentType = "text/json";
            httpWebRequest.Method = "GET";
            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();

        }
    }
}
RGarland
  • 31
  • 4
  • Hey, I've made a lib for Clockify API. You can find it [here](https://github.com/Morasiu/Clockify.Net) – Morasiu Feb 24 '20 at 10:27

1 Answers1

1

You’re setting the api key header on the ApiClient but then making your request with a newly createdHttpWebRequest which doesn’t then have the required api key header.

You should either make your request using the ApiClient or add the X-Api-Key header to theHttpWebRequest as follows:

httpWebRequest.Headers.Add(“X-Api-Key”, “********”)
Calvedos
  • 349
  • 2
  • 6
  • Thanks! That got me past that issue. I'm getting a 500 response now that I'm researching, but that got me authorized. – RGarland Apr 12 '19 at 15:51