I'm trying to use RestSharp to POST some data, however I'm encountering an error with my JSON content in the IRestResponse response.
Error:
"{"status":"error","message":"Invalid input JSON on line 1, column 96: Unexpected character ('e' (code 101)): was expecting comma to separate Object entries",...}"
From the message I assume I'm missing a comma at the end of the "content" line to separate the objects but can't figure out how to do it? Or do I need to place my name/value pairs into their own objects?
var client = new RestClient("https://api.com/APIKEY");
var request = new RestRequest(Method.POST);
request.AddHeader("accept", "application/json");
request.AddHeader("content-type", "application/json");
request.AddParameter("application/json", "{\"properties\":{" +
"\"pipeline\":\"0\"," +
"\"content\":\"<b>Email: </b>\"" + user.Email + "\"<br/><b>Error: </b>\"" + string.Join("<br/>", type.Name.Split(',').ToList()) + "\"<br/><b>UserId: </b>\"" + user.userId + "\"<br/><b>RequestId: </b>\"" + callbackData.idReference +
"\"subject\":\"Error for\"" + user.FirstName + " " + user.LastName +
"\"owner_id\":\"001\"}}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
You should never manually build your own JSON! You should use an (anonymous) object and a dedicated JSON serialiser like Json.Net.
That being said RestSharp allows you to specify an object as the parameter value for AddParameter but you should probably be using AddJsonBody for the request body.
There are several mistakes in your manual JSON generation like missing quotes and commas at the end of the "content" and "subject" lines.
var client = new RestClient("https://api.com/APIKEY");
var request = new RestRequest(Method.POST);
request.AddHeader("accept", "application/json");
request.AddHeader("content-type", "application/json");
var parameter = new
{
properties = new {
pipeline = "0",
content = $"<b>Email: </b>\"{user.Email}\"<br/><b>Error: </b>\"{string.Join("<br/>", type.Name.Split(',').ToList())}\"<br/><b>UserId: </b>\"{user.userId}\"<br/><b>RequestId: </b>\"{callbackData.idReference}",
subject = $"Error for \"{user.FirstName} {user.LastName}\"",
owner_id = "001"
}
};
request.AddJsonBody(parameter)
IRestResponse response = client.Execute(request);
Doing it this way is much less error prone.
Related
I have a rest request. The body is like the following:
RestClient client = new RestClient(uri);
RestRequest request = new RestRequest("", Method.POST);
request.AddHeader("Authorization", $"Bearer {myToken}");
request.AddHeader("Content-type", "application/json");
string json = "{'body': {'contentType': 'html','content': '" + message + "'}}";
request.AddJsonBody(json);
IRestResponse response = client.Execute(request);
The message contains apostrophes, like John's so the json will be
string json = "{'body': {'contentType': 'html','content': 'John's'}}";
This gives an error, Bad Request.
How can i accommodate for this and any other special characters in the message
you have to replace ' with \ "
string json= "{\"body\": {\"contentType\": \"html\",\"content\": \""+message+"\"}}";
I need help ...
When I use Postaman the 2 requests I make work correctly, but this code of mine only returns me the authentication correctly but when I create a new request, it does not return anything. The response_1 content returns this error: "{" error_code ":" platform.web_application "," correlation_id ":" d7em3oxz7ng6kh9qx977l3904 "," description ":" HTTP 404 Not Found "," description_translated ":" HTTP 404 Not Found ", "properties": null, "business_error": false} "
and the ResponseUri of response_1 is concatenated with that of the authentication. I can't find the error.This is the c# code
var client = new RestSharp.RestClient(url + #"/authentication/sign_in");
var request = new RestSharp.RestRequest(RestSharp.Method.POST);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "application/json");
request.AddParameter("application/json", request.AddJsonBody(new { user = admUserPass[0], password = admUserPass[1] }), RestSharp.ParameterType.RequestBody);
ServicePointManager.SecurityProtocol = (SecurityProtocolType)768 | (SecurityProtocolType)3072;
RestSharp.IRestResponse response = client.Execute(request);
//response.StatusCode = "OK"
request.Resource = url + #"/admin/users";
request.Method = RestSharp.Method.GET;
foreach (var cookie in response.Cookies)
{
request.AddCookie(cookie.Name, cookie.Value);
}
request.AddHeader("content-type", "application/json");
request.AddHeader("Accept", "application/json");
RestSharp.IRestResponse response_1 = client.Execute(request);
Create a new Request before executing the second client.Execute(...)
OK I found the solution, my code is right but I am working to consume the Octane ALM API rest.
adding this line in the request header "request.AddHeader("ALM_OCTANE_TECH_PREVIEW "," true ");"
The request is working correctly. There is a discussion at this link https://community.microfocus.com/adtd/alm_octane/f/ngabetageneralbetaforum/161440/alm_octane_tech_preview-header-issue
This is my first time working with APIs and I'd really appreciate your help and patience on bearing with me.
I'm making a GET request to the client Synccentric for getting data [Given URL below I'm using for ref].
https://api.synccentric.com/?version=latest#cb8d3255-7639-435e-9d17-c9e962c24146
[Update]
I found a way to attach parameters to querystrings and the response was validated. I'm still stuck with passing the array of fields.
var client = new RestClient("https://v3.synccentric.com/api/v3/products");
var request = new RestRequest(Method.GET);
Console.WriteLine("**** Adding Headers, Content Type & Auth Key ****");
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Authorization", "Bearer {{MyAPIToken}}");
request.AddParameter("campaign_id", 12618);
request.AddParameter("downloadable", 1);
request.AddParameter("downloadable_type", "csv");
string[] fields = new[] { "asin", "upc", "actor", "all_categories", "is_eligible_for_prime", "listing_url" };
request.AddParameter("fields", fields);
IRestResponse response = client.Execute(request);
I think I know where the problem is
So the [5]th parameter should ideally hold this value "[\n \"asin\",\n \"upc\",\n \"additional_image_1\",\n \"category\",\n \"is_eligible_for_prime\",\n \"listing_url\"\n ]"
But instead it looks like this.
Can you guys help me with this?
I tried the API call using Python and referencing the documents and I did get the desired response.
Attaching the python block below:
import requests
url = 'https://v3.synccentric.com/api/v3/products'
payload = "{\n \"campaign_id\": 12618,\n \"fields\": [\n \"asin\",\n \"upc\",\n \"additional_image_1\",\n \"category\",\n \"is_eligible_for_prime\",\n \"listing_url\"\n ]\n} #\"downloadable\":1,\n \"downloadable_type\":\"csv\"\n}"
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer {{MyAPIToken}}'
}
response = requests.request('GET', url, headers = headers, data = payload, timeout= 100000 , allow_redirects= 0)
print(response.text)
After the execution I got the response I was looking for.
RestSharp will not allow you to send a GET request with a content-body. The error says it all.
You will have to send the parameters as query parameters.
Console.WriteLine("**** Starting Synccentric API Fetch ****");
var client = new RestClient("https://v3.synccentric.com/api/v3/products");
var request = new RestRequest(Method.GET);
Console.WriteLine("**** Adding Headers, Content Type & Auth Key ****");
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Authorization", "Bearer {{MyAPIToken}}");
Console.WriteLine("**** Adding parameters ****");
request.AddParameter("campaign_id", 12618);
request.AddParameter("downloadable", "true");
request.AddParameter("downloadable_type", "CSV");
var fields = new[] { "asin", "upc", "actor", "all_categories" };
foreach (var field in fields)
{
request.AddParameter("fields", field);
}
IRestResponse response = client.Execute(request);
This will build you the following query string, which should be sent and hopefully understood okay.
https://v3.synccentric.com/api/v3/products?campaign_id=12618&downloadable=True&downloadable_type=CSV&fields=asin&fields=upc&fields=actor&fields=all_categories
UPDATE Having looked at the comments, it may be that RestSharp cannot be used with that API as it seems that it requires content body with a GET request!
I want to sent a base64pdf, via http put.
Unfortunatly I get the 400 bad request error.
I tried it with the google rest api and there it worked fine.
string finalURL = upURL + pdf.Id + "/signedpdf";
string json = "{ 'base64Pdf' : '" + pdf.Base64Pdf + "' }";
using (var client = new HttpClient())
{
var response = await client.PutAsync(finalURL, new StringContent(json, Encoding.UTF8, "application/json"));
if (response.IsSuccessStatusCode)
return true;
}
It works when I create the Json by Javascriptserializer.
TransferObject to = new TransferObject(pdf.Base64Pdf);
var json2 = new JavaScriptSerializer().Serialize(to);
I believe the JSON standard only supports double quote characters. Your code is using single quote characters in your concatenated JSON. Base64 encoded string will not contain double quote characters so you should be good there. Try this:
string json = "{ \"base64Pdf\" : \"" + pdf.Base64Pdf + "\" }";
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");