Home > Enterprise >  Restsharp GET Call Works, but POST is Unauthorized?
Restsharp GET Call Works, but POST is Unauthorized?

Time:12-04

I'm working on a RestSharp API caller for challonge.com, and I've run into a problem with authorization. When making a GET call, everything works properly and I can acquire the information I need. However, when attempting a POST call, the status code returns as Unauthorized, despite using the same API key. I've tried including the key in the request body and as a parameter, but neither seem to work.

Here are the calls that I am making:

-GET: https://api.challonge.com/v1/documents/tournaments/index

-POST: https://api.challonge.com/v1/documents/tournaments/create

And here is my code.

public class APICall
    {
        HttpUtility http = new HttpUtility();
        RestClient client = new RestClient("https://api.challonge.com/v1/");
        public string GetCall(string key)
        {
            client.AddDefaultHeader("Content-Type", "application/json");
            RestRequest request = new RestRequest("tournaments", DataFormat.Json);
            request.AddParameter("api_key", key);
            IRestResponse response = client.Get(request);
            return response.StatusCode.ToString();
        }
        public string PostCall(string tournName, string key)
        {
            client.AddDefaultHeader("Content-Type", "application/json");
            RestRequest request = new RestRequest("tournaments", DataFormat.Json);
            var obj = new Tournament(tournName,key);
            //request.AddParameter("api_key", key);
            request.AddJsonBody(obj);
            IRestResponse response = client.Post(request);
            return response.StatusCode.ToString();
        }
    }

CodePudding user response:

Authentication

All interactions with the API require a Challonge account with a verified email address and API key. We support HTTP basic authentication. Username = your Challonge username, Password = your API key. Many clients format these requests as: https://username:[email protected]/v1/... Or, if you prefer, you can just pass your API key as parameter api_key to all method calls.

So this should work at the start of your PostCall:

var userName = "your Challonge username";
var uNamePw = $"{userName}:{key}";

var encoding = Encoding.GetEncoding("ISO-8859-1");
var credentials = Convert.ToBase64String(encoding.GetBytes(uNamePw));

client.AddDefaultHeader("Authorization", $"Basic {credentials}");

Alternatively you should be able to append ?api_key={your api key} to the url

  • Related