Search code examples
c#apirestrestsharp

RestSharp authentication with Api Id and Api Key


I have to call a restful API, but the only details I have are an API ID and an API key.

I am trying to use Restsharp library code like this.

  var client = new RestClient("https://xxxxxxx");
  client.Authenticator = new HttpBasicAuthenticator("xxxxx", "yyyyyy");

I get a 401 authorization required error.

Could you please point me in the right direction.

Thanks.


Solution

  • Here is the solution that i came up with.

    this returns the client object

    private RestClient InitializeAndGetClient()
            {
                var cookieJar = new CookieContainer();
                var client = new RestClient("https://xxxxxxx")
                {
                    Authenticator = new HttpBasicAuthenticator("xxIDxx", "xxKeyxx"),
                    CookieContainer = cookieJar
                };
    
                return client;
            }
    

    and you can use the method like

                var client = InitializeAndGetClient();
                var request = new RestRequest("report/transaction", Method.GET);
    
                request.AddParameter("option", "value");
    
    
    
                //Run once to get cookie.
                var response = client.Execute(request);
    
                //Run second time to get actual data
                response = client.Execute(request);
    

    Hope this helps you.

    Prakash.