Hi
In below code Token is generated . I want it to be a separate class or function. How it can be done
C#
var client = new RestClient("api.nimbuspost.com/v1/users/login");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("content-type", "application/json");
var body = @"{" + "\n" +
@" ""email"" : ""[email protected]""," + "\n" +
@" ""password"" : ""T34!""" + "\n" +
@"}";
request.AddParameter("application/json", body, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
dynamic json = JsonConvert.DeserializeObject(response.Content);
string token = json.data;Thanks

Amit MohantyRank #112 · 20K reputationPosted Dec 25, 2022, 11:04 PM EST
Check this
public string GetToken(string postBody) { var client = new RestClient("api.nimbuspost.com/v1/users/login"); client.Timeout = -1; var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); var body = postBody; request.AddParameter("application/json", body, ParameterType.RequestBody); IRestResponse response = client.Execute(request); dynamic json = JsonConvert.DeserializeObject(response.Content); return json.data; }Vishal JoshiRank #377 · 6.7K reputationPosted Dec 26, 2022, 4:49 AM EST
Hello
You can use the below class and it's a generic function to make it work for all API calls.
public static class RestAPICall { public static RestResponse POSTRequest(string URL, string Body){ var client = new RestClient(URL); client.Timeout = -1; var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); request.AddParameter("application/json", body, ParameterType.RequestBody); RestResponse response = client.Execute(request); return response; } public static RestResponse GETRequest(string URL, string Body) { var client = new RestClient(URL); client.Timeout = -1; var request = new RestRequest(Method.GET); RestResponse response = client.Execute(request); return response; } } Public Class yourclassToCallAPI { string GetTokenURL = "api.nimbuspost.com/v1/users/login"; string GetTokenBody = @"{" + "\n" + @" ""email"" : ""[email protected]""," + "\n" + @" ""password"" : ""T34!""" + "\n" + @"}" public void yourMethod() { RestResponse responseObj = RestAPICall.POSTRequest(GetTokenURL, GetTokenBody); dynamic json = JsonConvert.DeserializeObject(responseObj .Content); string token = json.data; console.writeLine("Token: " + token); } }Thank you