I am working with RestSharp and an API I believe is set up with Azure. I making a POST request to the API, but have noted that the request only works when the body is named, "agentGetRequest" in Postman.
Bad Body:
{
"supplierKey": "XXXX-XXXX-XXXX-XXXX",
"inputDate": "2021-01-17T00:00:00.000Z"
}
Good Body:
{
"agentGetRequest": {
"supplierKey": "XXXX-XXXX-XXXX-XXXX",
"inputDate": "2021-01-17T00:00:00.000Z"
}
}
So when I run my code
void Post(AgentRequest agentRequest, Credentials creds )
{
Uri baseUrl = new Uri(creds.baseURL);
IRestClient client = new RestClient(baseUrl);
IRestRequest request = new RestRequest(ENDPOINT, Method.POST);
request.AddHeader("subscriptionKey", creds.subscriptionKey);
// Option 1:
request.AddJsonBody(agentRequest);
// Option 2:
request.AddJsonBody(agentRequest, "agentGetRequest")
IRestResponse<GetAgentResponse> response = client.Execute<GetAgentResponse>(request);
if (response.IsSuccessful)
{
Console.WriteLine(JsonConvert.SerializeObject(response.Content));
}
else
{
Console.WriteLine(response.ErrorMessage);
}
}
// Body request object
public class AgentRequest
{
public string inputDate { get; set; }
public string supplierKey { get; set; }
}
It throws a bad request error because it can't find the body, "agentRequest."
I have found a workaround where I feed it a string as the body - but this would hate to have to do this for every endpoint:
// Instead of request.AddJsonBody()...
string body = "{\"agentGetRequest\": {\"supplierKey\": \"XXXX-XXXX-XXXX-XXXX\",\"inputDate\": \"2021-0117T00:00:00.000Z\"}}";
request.AddParameter("application/json", body, ParameterType.RequestBody);
How can I correctly format the body when adding it via AddJsonBody to include the name (and maybe the encapsulating brackets)?
Recording to the accepted answer of RestSharp Post a JSON Object, you could add JSON body like below:
request.AddJsonBody(
new
{
agentGetRequest = agentRequest
}); // AddJsonBody serializes the object automatically