Burgaz
Burgaz

Reputation: 257

Post RestSharp Google API Error

I'm trying to access YouTube API using RestSharp. While POSTing I'm getting error code:400 with the following reason: "This API does not support parsing form-encoded input". Below is a short snippet of my code:

var client = new RestClient("https://www.googleapis.com");
var request = new RestRequest(Method.POST);
request.Resource = "youtube/v3/liveBroadcasts";
request.RequestFormat = DataFormat.Json;
request.AddParameter("part", "snippet,status");
request.AddParameter("key", "MyClientId");
request.AddHeader("Authorization", "Bearer " + "MyAccessCode");
request.AddHeader("Content-Type", "application/json; charset=utf-8");
request.AddBody(aJson);

try
{
var response = client.Execute(request);
Console.WriteLine(response.Content);
}
catch (Exception e)
{
Console.WriteLine(e);
} 

The response content as describe above was "This API does not support parsing form-encoded input" In the Json that I'm sending (aJson) looks like that:

{
"snippet": {
"scheduledEndTime": "2015-01-10T12:11:11.0+0400",
"scheduledStartTime": "2015-01-10T11:11:11.0+0400",
"title": "MyBroadcastName"
},
"kind": "youtube#liveBroadcast",
"status": {
"privacyStatus": "private"
}
}

I'll be glad to get any assistance related to the above request. What am I doing wrong?

thanks, R.

Upvotes: 2

Views: 1001

Answers (2)

Todd Menier
Todd Menier

Reputation: 39329

The problem is with your calls to request.AddParameter. You want those appended the URL as query parameters, but when the HTTP method is POST, RestSharp will send them as URL-encoded form data by default. You want something like this:

request.Resource = "youtube/v3/liveBroadcasts?part={part}&key={key}";
request.AddParameter("part", "snippet,status", ParameterType.UrlSegment);
request.AddParameter("key", "MyClientId", ParameterType.UrlSegment);

Upvotes: 3

Burgaz
Burgaz

Reputation: 257

Thanks to Todd and after some additional digging I found the problem. below is the fixed code:

var client = new RestClient("https://www.googleapis.com");
var request = new RestRequest(Method.POST);
request.RequestFormat = DataFormat.Json;
request.Resource = "youtube/v3/liveBroadcasts?part={part}&key={key}";
request.AddParameter("part", "snippet,status", ParameterType.UrlSegment);
request.AddParameter("key", "MyClientId", ParameterType.UrlSegment);
request.AddHeader("Authorization", "Bearer " + "MyAccessCode");
request.AddHeader("Content-Type", "application/json; charset=utf-8");
request.AddBody(anObject); //<== Here you should use an object and NOT a json. RestSharp will do the serialization!

try
{
var response = client.Execute(request);
Console.WriteLine(response.Content);
}
catch (Exception e)
{
Console.WriteLine(e);
} 

Thanks for your assistance. R.

Upvotes: 2

Related Questions