BadRequest when PUT JSON data on Firebase REST API - c#

I have this code that I am using to PUT my JSON string on Firebase database:
RestRequest request = new RestRequest("MemberAndChannels/{userId}/{channelId}.json", Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddParameter("auth", accessKey);
request.AddUrlSegment("userId", user.UUID);
request.AddUrlSegment("channelId", channel.UUID);
request.AddHeader("Content-Type", "application/json; charset=utf-8");
request.AddJsonBody(channelJson);
IRestResponse response = client.Execute(request);
if (response.StatusCode == HttpStatusCode.OK)
{
}
else {
}
But I am getting following error (StatusCode: BadRequest):
"{\n \"error\" : \"Invalid data; couldn't parse JSON object, array, or value.\"\n}\n"
I've tried PUTing same data using curl and it worked. Can't figure out where I am doing wrong.

The object is being serialized twice (double serialized).
Pass the channel object as it is to AddJsonBody and the request will serialize it to JSON before sending body
request.AddJsonBody(channel);
assuming here channel is an object of a Class

I have modified the code with slight changes. Please try with this
RestRequest request = new RestRequest("MemberAndChannels/{userId}/{channelId}.json", Method.POST);
request.AddParameter("auth", accessKey); // or request.AddHeader("auth", accessKey);
request.AddUrlSegment("userId", user.UUID);
request.AddUrlSegment("channelId", channel.UUID);
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Accept", "application/json");
request.AddParameter("application/json", channelJson, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
if (response.StatusCode == HttpStatusCode.OK)
{
}
else {
}

I had the same problem.
I soved it changing this code:
request.AddParameter("auth", accessKey);
by
request.AddQueryParameter("auth", accessKey);
I hope help you.
Regards

Related

Token Autorization in RestSharp does not appear

Good morning, I'm retrieving an authorization token using RestSharp, but instead of returning a Token, it returns an html page:
var client = new RestClient("https://iam.efatura.cv/auth/realms/taxpayers/ protocol/openid- connect/auth"); var request = new RestRequest(Method.POST); request.AddHeader("grant_type", "authorization_code"); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddHeader("accept", "application/json"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=client_credentials&client_id=adadasdasdasdasda& scope=openid&clientSecretasdadsdadasdasdasdasdasdasdasasd& redirect_uri=https://iam.efatura.cv/auth/realms/taxpayers", ParameterType.RequestBody); IRestResponse response = client.Execute(request); Token=response.Content;

How to capture Json from web site using c#

I have a paid subscription to Seeking Alpha and have a cookkie which enables me to get full data from https://seekingalpha.com/symbol/AAPL/financials-data?period_type=quarterly&statement_type=income-statement&order_type=latest_left&is_pro=True
I'd like to collect JSON response using C#
Below is my horrible code
string cookie = "my super secret cookie string";
var request = new RestRequest(Method.GET);
request.AddHeader("content-type", "application/json");
request.AddHeader("Accept", "*/*");
request.AddHeader("User-Agent","Mozilla/5.0");
request.AddHeader("X-Requested-With", "XMLHttpRequest");
string url = "https://seekingalpha.com/symbol/AAPL/financials-data?period_type=quarterly&statement_type=income-statement&order_type=latest_left&is_pro=True";
request.AddParameter("cookie", cookie, ParameterType.Cookie);
var client = new RestClient(url);
var queryResult = client.Execute(request);
Console.WriteLine(queryResult.Content);
How can I get it to return JSON to me? I am getting something but not the JSON I want
Try updating your Access header to application/json.
request.AddHeader("Accept", "application/json");
Accept indicates what kind of response from the server the client can accept.
You can get more info for Accept from Header parameters: “Accept” and “Content-type” in a REST context
After poking around for a bit I figured it out. For the benefit of all:
private bool FinancialStatement(string symbol, string statement, string period)
{
var target = $"{BASE_URL}{symbol}/financials-data?period_type={period}&statement_type={statement}&order_type=latest_left&is_pro=True";
var client = new RestClient(target);
client.Timeout = -1;
var request = new RestRequest(Method.GET);
request.AddHeader("Cookie", MACHINE_COOKIE);
IRestResponse response = client.Execute(request);
dynamic responseObj;
try
{
responseObj = JsonConvert.DeserializeObject(response.Content);
}
catch (Exception)
{
return false;
}
return response.IsSuccessful;
}

How to fix 400 Response Incoming from Microsoft Azure Computer Vision service

I subscribed to Computer Vision API on RapidAPI. When I'm testing the API on the RapidAPI platform, it's working perfectly. But when I'm calling it from my app, it responding 400 Bad request.
How can I fix this problem?
I'm using the RESTSharp library.
Here's my code -
public static IRestResponse GetClassifiedImageData()
{
var client = new RestClient("{Client Path}");
var request = new RestRequest(Method.POST);
request.AddHeader("x-rapidapi-host", "{Rapid API host}");
request.AddHeader("x-rapidapi-key", "{My API key}");
request.AddHeader("content-type", "application/json");
request.AddHeader("accept", "application/json");
request.AddParameter("application/json", "{\"url\":\"Image URL\"}", ParameterType.RequestBody);
return client.Execute(request);
}
And if I call asyncronusly, I get this message -
System.Runtime.CompilerServices.AsyncTaskMethodBuilder1+AsyncStateMachineBox1[System.String,ComputerVision.Program+d__2]
Async Code-
public static async Task<IRestResponse> GetClassifiedImageData2()
{
var client = new RestClient("{Client Path}");
var request = new RestRequest(Method.POST);
request.AddHeader("x-rapidapi-host", "{Rapid API host}");
request.AddHeader("x-rapidapi-key", "{My API key}");
request.AddHeader("content-type", "application/json");
request.AddHeader("accept", "application/json");
request.AddParameter("application/json", "{\"url\":\"Image URL\"}", ParameterType.RequestBody);
return await client.ExecuteAsync(request);
}
I've tried these -
Restarting Visual Studio.
Cleaning Temp and prefetch files.
Based on my test, it is the URL encoding that is causing the problem.
You may use the code sample from Rapid API website. However, while using RestClient, you should not urlencode the urlpath. The Rapid API engineer may make a mistake here. In most case, a , character does not need to be urlencoded. So, you can directly use https://microsoft-azure-microsoft-computer-vision-v1.p.rapidapi.com/analyze?visualfeatures=Categories,Tags,Color,Faces,Description as the path string.
And, anyway, the correct encoded string is https://microsoft-azure-microsoft-computer-vision-v1.p.rapidapi.com/analyze?visualfeatures=Categories%2cTags%2cColor%2cFaces%2cDescription
The code sample from Rapid API:
I used the sample, and got the same error message as yours. But I solved it by using the original string or the correct encoded string:
public static async Task<IRestResponse> GetClassifiedImageDataAsync()
{
// The correct encoded string will work
//var client = new RestClient("https://microsoft-azure-microsoft-computer-vision-v1.p.rapidapi.com/analyze?visualfeatures=Categories%2cTags%2cColor%2cFaces%2cDescription");
// The original string will work
var client = new RestClient("https://microsoft-azure-microsoft-computer-vision-v1.p.rapidapi.com/analyze?visualfeatures=Categories,Tags,Color,Faces,Description");
var request = new RestRequest(Method.POST);
request.AddHeader("x-rapidapi-host", "microsoft-azure-microsoft-computer-vision-v1.p.rapidapi.com");
request.AddHeader("x-rapidapi-key", "71a69********************************3ddb");
request.AddHeader("content-type", "application/json");
request.AddHeader("accept", "application/json");
request.AddParameter("application/json", "{\"url\":\"https://upload.wikimedia.org/wikipedia/commons/1/11/Kanye_West_at_the_2009_Tribeca_Film_Festival.jpg\"}", ParameterType.RequestBody);
return await client.ExecuteAsync(request);
}
static void Main(string[] args)
{
var result = GetClassifiedImageDataAsync().GetAwaiter().GetResult();
Console.WriteLine(result.Content);
}
And you can also use RestClient's method to add query string:
public static async Task<IRestResponse> GetClassifiedImageDataAsync()
{
// Without query string
var client = new RestClient("https://microsoft-azure-microsoft-computer-vision-v1.p.rapidapi.com/analyze");
var request = new RestRequest(Method.POST);
// Add as query string manually
request.AddParameter("visualfeatures", "Categories,Tags,Color,Faces,Description", ParameterType.QueryString);
request.AddHeader("x-rapidapi-host", "microsoft-azure-microsoft-computer-vision-v1.p.rapidapi.com");
request.AddHeader("x-rapidapi-key", "71a69********************************3ddb");
request.AddHeader("content-type", "application/json");
request.AddHeader("accept", "application/json");
request.AddParameter("application/json", "{\"url\":\"https://upload.wikimedia.org/wikipedia/commons/1/11/Kanye_West_at_the_2009_Tribeca_Film_Festival.jpg\"}", ParameterType.RequestBody);
return await client.ExecuteAsync(request);
}
And the successful result:

C# Restsharp GET Method Request will show "No JSON object could be decoded"

I am using C# winform on Visual Studio 2019 and using RestSharp.
I have tested WEBAPI function on POSTMAN with correct output.
So i try to implement on C# Winform.
I dump POSTMAN code (C# Restsharp) as following:
var client = new RestClient("http://192.168.2.10:88/en/product/ajax_api_getProductInfoBatch");
var request = new RestRequest(Method.GET);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("Connection", "keep-alive");
request.AddHeader("Content-Length", "21");
request.AddHeader("Accept-Encoding", "gzip, deflate");
request.AddHeader("Host", "192.168.2.10:88");
request.AddHeader("Postman-Token", "f1ff99c7-dc02-40cb-b87a-
a046cf106a96,e2b7d88d-cfc9-4c99-8117-ec48398e56ed");
request.AddHeader("Cache-Control", "no-cache");
request.AddHeader("Accept", "*/*");
request.AddHeader("User-Agent", "PostmanRuntime/7.18.0");
request.AddParameter("undefined", "{\n \"Item No\":\"3101\"\n}",
ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
and i revised
request.AddParameter("undefined", "{\n \"Item No\":\"3101\"\n}"
to
request.AddParameter("application/json", "{\"Item No\":\"3101\"}", ParameterType.RequestBody);
Therefore, the full code will be
private void Button1_Click(object sender, EventArgs e)
{
var client = new RestClient("http://192.168.2.10:88/en/product/ajax_api_getProductInfoBatch");
var request = new RestRequest(Method.GET);
//request.AddHeader("cache-control", "no-cache");
//request.AddHeader("Connection", "keep-alive");
//request.AddHeader("Content-Length", "22");
//request.AddHeader("Accept-Encoding", "gzip, deflate");
//request.AddHeader("Host", "192.168.2.10:88");
//request.AddHeader("Postman-Token", "86e877f8-5755-4e57-960a-eaa78b1e8b6c,da863548-65e0-4053-9cb3-b5760da94165");
//request.AddHeader("Cache-Control", "no-cache");
//request.AddHeader("Accept", "*/*");
//request.AddHeader("User-Agent", "PostmanRuntime/7.18.0");
//request.AddHeader("Content-Type", "text/plain");
request.AddParameter("application/json", "{\"Item No\":\"3101\"}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
var content = response.Content;
textBox1.Text = content;
}
but it is still output "No JSON object could be decoded" after GET request.
Anyone share your experience will be appreciated.
or there are other ways to do GET/POST on C#.
thanks.!
You can use httpclient and pass parameters as stringcontent and type should be application/json for stringcontent.
This is for post request

How to add json to RestSharp POST request

I have the following JSON string that is passed into my c# code as a string parameter - AddLocation(string locationJSON):
{"accountId":"57abb4d6aad4","address":{"city":"TEST","country":"TEST","postalCode":"TEST","state":"TEST","street":"TEST"},"alternateEmails":[{"email":"TEST"}],"alternatePhoneNumbers":[{"phoneNumber":"TEST"}],"alternateWebsites":[{"website":"TEST"}],"auditOnly":false,"busName":"593163b7-a465-43ea-b8fb-e5b967d9690c","email":"TEST EMAIL","primaryKeyword":"TEST","primaryPhone":"TEST","rankingKeywords":[{"keyword":"TEST","localArea":"TEST"}],"resellerLocationId":"5461caf7-f52f-4c2b-9089-2ir8hgdy62","website":"TEST"}
I'm trying to add the JSON to a RestSharp POST request like this but it's not working:
public string AddLocation(string locationJSON)
{
var client = new RestClient(_authorizationDataProvider.LocationURL);
var request = new RestRequest(Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddHeader("cache-control", "no-cache");
request.AddHeader("Authorization", _authorizationResponse.Token);
...
request.AddJsonBody(locationJSON);
var response = client.Execute(request);
}
The response comes back as "Bad Request". Here is what I get if I inspect the response in the debugger:
{"code":"invalid_json","details":{"obj.address":[{"msg":["error.path.missing"],"args":[]}],"obj.rankingKeywords":[{"msg":["error.path.missing"],"args":[]}],"obj.alternatePhoneNumbers":[{"msg":["error.path.missing"],"args":[]}],"obj.busName":[{"msg":["error.path.missing"],"args":[]}],"obj.accountId":[{"msg":["error.path.missing"],"args":[]}],"obj.alternateEmails":[{"msg":["error.path.missing"],"args":[]}],"obj.alternateWebsites":[{"msg":["error.path.missing"],"args":[]}],"obj.email":[{"msg":["error.path.missing"],"args":[]}],"obj.primaryKeyword":[{"msg":["error.path.missing"],"args":[]}],"obj.auditOnly":[{"msg":["error.path.missing"],"args":[]}]}}
I have inspected the request parameters after calling AddJsonBody and the value appears to be including the escape sequence for double quotes - which seems to be the issue.
{\"accountId\":\"57abb4d6aad4def3d213c25d\",\"address\":{\"city\":\"TEST\",\"country\":\"TEST\",\"postalCode\":\"TEST\",\"state\":\"TEST\",\"street\":\"TEST\"},\"alternateEmails\":[{\"email\":\"TEST\"}],\"alternatePhoneNumbers\":[{\"phoneNumber\":\"TEST\"}],\"alternateWebsites\":[{\"website\":\"TEST\"}],\"auditOnly\":false,\"busName\":\"84e7ef98-7a9f-4805-ab45-e852a4b078d8\",\"email\":\"TEST EMAIL\",\"primaryKeyword\":\"TEST\",\"primaryPhone\":\"TEST\",\"rankingKeywords\":[{\"keyword\":\"TEST\",\"localArea\":\"TEST\"}],\"resellerLocationId\":\"06b528a9-22a6-4853-8148-805c9cb46941\",\"website\":\"TEST\"}
so my question is how do I add a json string to the request body?
I've ran into this problem as well. Try something like this instead of AddJsonBody.
request.AddParameter("application/json", locationJSON, ParameterType.RequestBody);
This should work:
request.AddParameter("application/json; charset=utf-8", JsonConvert.SerializeObject(yourObject), ParameterType.RequestBody);
If you directly add the serialized object, the problem is the Json convert is adding "\" before each ".
I have tried like this and it working fine, Add Bearer with token
request.AddHeader("cache-control", "no-cache");
request.AddHeader("authorization", "Bearer " + "your token key");
request.AddHeader("accept", "application/json");

Categories

Resources