I'm writing an automation test. I've got an endpoint URL 'https://deckofcardsapi.com/api/deck/new/shuffle/?deck_count=1' when I go onto this endpoint there is text that is printed.
Is there any way in my test I can validate some of the data within the text that is printed. For example, validate when I go to the endpoint remaining is 52.
{
"deck_id":"qzpre4zxokj7",
"shuffled":true,
"remaining":52,
"success":true
}
You can use the JSON parser to extract the remaining value.
NuGet Package :
Newtonsoft.Json
I assumed you are getting the below text in your response.So, please use the below code to extract the remaining value
{
"deck_id":"qzpre4zxokj7",
"shuffled":true,
"remaining":52,
"success":true
}
Code:
var expectedValue =52;
var apiResponse = <<Stroe the API Text Response>>;
var jsonObject = JObject.Parse(apiResponse);
var remaining = jsonObject["remaining"].ToString();//It will retrun the value as 52
var actualValue = Int64.Parse(remaining);
Assert.AreEqual(expectedValue, actualValue);//Validate the remaing Value from the API Response
That is likely a "REST" endpoint. When you do a GET from that endpoint, it is returning with "JSON" (JavaScript Object Notation). What you are seeing is an object returned in JSON format. The object has 4 properties (deck_id, shuffled, remaining, and success). The value of "remaining" is 52. Find a JSON parser and you should be able to see this.
If you search the internet, you should find Selenium tools that can parse JSON (sorry, I'm not an expert in that technology).
Related
I am using RestClient to pass JSON paramter into api in C#.But I am getting response
"An unexpected 'StartObject' node was found for property named
'InputArguments' when reading from the JSON reader. A 'PrimitiveValue'
node was expected"
I am using below code in C#
var client_startRobot = new RestClient("https://xxxx.xxxx.com/odata/Jobs/UiPath.Server.Configuration.OData.StartJobs");
var request_startRobot = new RestRequest(Method.POST) ;
request_startRobot.AddParameter("Authorization", string.Format("Bearer " + result), ParameterType.HttpHeader);
request_startRobot.AddHeader("content-type", "application/json");
string parameter = "{\"startInfo\":{\"ReleaseKey\": \"ds32rd1-6c98-42f542d-23bb8111ac91d\",\"RobotIds\": [1],\"JobsCount\": 0,\"Strategy\": \"Specific\",\"InputArguments\": {\"add_name\": \"xxxxx-xxx-\"}}}";
request_startRobot.AddParameter("application/json; charset=utf-8", parameter, ParameterType.RequestBody);
IRestResponse response_startRobot = client_startRobot.Execute(request_startRobot);
This seems to be a question of reading the API documentation carefully. Assuming you are trying to call an orchestrator as described here, I find this example that looks a lot like yours.
{ "startInfo":
{ "ReleaseKey": "5b754c63-5d1a-4c37-bb9b-74b69e4934bf",
"Strategy": "Specific",
"RobotIds": [ 1553 ],
"NoOfRobots": 0,
"Source": "Manual",
"InputArguments": "{\"message\":\"Aloha\"}"
}
}
Note that the InputArguments value is actually a simple string, not actual JSON (the string contains an escaped JSON string).
Your request looks like this:
"InputArguments": {"add_name": "xxxxx-xxx-"}
When according to the example given, it should look like this:
"InputArguments": "{\"add_name\": \"xxxxx-xxx-\"}"
It looks like you will have to "double escape" this part of your string, something like this:
\"InputArguments\": \"{\\\"add_name\\\": \\\"xxxxx-xxx-\\\"}\"
Actually building up a strongly typed request object and leaving the serialization to your REST client might make things easier to read.
I got this error, and I had regardingobjectid propery, which I suspected it might have been caused the error, even though it seemed to be fine codding,
finally I relized that the problem was with another field
task["subject"] = data.subject;
data was dynamic, yet in logging it you got string value, but when assigning it you get a dynamic value. I fixed this line as following
task["subject"] = (string)data.subject
and the error disappeared :)
I have created a basic ASP.Net Web Application and I am trying to use the OpenWeatherMap API with this. (first time dealing with APIs).
The Info I have about the WebAPI is:
You can search weather forecast for 5 days with data every 3 hours by city name. All weather data can be obtained in JSON and XML formats.
There is a possibility to receive a central district of the city/town with its own parameters (geographic coordinates/id/name) in API response. Example
API call:
api.openweathermap.org/data/2.5/forecast?q={city name},{country code}
Parameters:
q city name and country code divided by comma, use ISO 3166 country codes
Examples of API calls:
api.openweathermap.org/data/2.5/forecast?q=London,us&mode=xml
Currently I have this working when I use the api that returns a json object
api.openweathermap.org/data/2.5/weather?q=London&units=metric
However if I simply change the URL to the first (which returns the XML) my application no longer retrieves the data from the API.
I have tried amended the mode=xml into mode=json but still no avail.
How can I use the first web API?
Many thanks
--Edit:
In my model class i have the following method:
string url = "api.openweathermap.org/data/2.5/…;
var client = new WebClient();
var content = client.DownloadString(url);
var serializer = new JavaScriptSerializer();
var jsonContent = serializer.Deserialize<Object>(content);
return jsonContent;
(taken out the key) I then call this method from my view. However I cannot use that api call that has the =xml at the end
your problem is when result is returned as xml, you are using a JavaScriptSerializer to Deserialize it.
xml is not json, hence the Deserialization would have failed
what you need is a XmlSerializer to deserializae the result
below is some code to get you started:
string url = #"http://samples.openweathermap.org/data/2.5/forecast?q=London&appid=b1b15e88fa797225412429c1c50c122a1&mode=xml";
var client = new WebClient();
var content = client.DownloadString(url);
XmlSerializer serializer = new XmlSerializer(typeof(weatherdata));
weatherdata result = null;
using (TextReader reader = new StringReader(content))
{
result = (weatherdata)serializer.Deserialize(reader);
}
notice that typeof weatherdata - it is no point of Deserialize into non strong type object if you are going to deserialize into object,
there is noting you can do with it.
if you don't want to hand code the strong type model, copy the xml result into clipboard then use VS (not sure other version but 2017 as example) toolbar
Edit -> paste special -> Paste xml as classes to generate the strong type class for you
I am new to asp .net and doing some homeproject. Hope you can help!
I have a ASP.NET Web API application with texbox that takes order number as serch string.
I find my object with this code:
var query = ReadFiles()
.Where(n => n.orderNumber == TextBox1.Text)
.Select(n => n);
After that Im trying to convert it to JSON witht his code:
var json = new JavaScriptSerializer().Serialize(query);
TextBox1.Text = json;
I get a String back that says: JSON Visualizer
Now for the question. How do I get this JSON string to the UI, I would like it to show up in some sort of table? I am new to asp .net with that in mind I hope this question is not to stupid. Oh and I use C#
Kind regards.
If you are using a Web API controller class, you can create a method endpoint that returns the data, and then use an Ajax request on the client to that end point.
This is a nice example: Getting Started with ASP.NET Web API 2. You should also look at Routing in ASP.NET Web API to understand the routing mechanism.
In your particular case, you could set up an endpoint to post the order number to from the client's text box (using Ajax). The controller method will then receive the order number as a parameter, and then fetch the data it needs on the server. You would then return the JSON response from that method. The client's success callback function from the post call will receive the JSON response, and then it's up to you to bind that to the markup with JavaScript.
I wanna get a raw json string from my client in my WebAPI application.
I tried it like this :
public string Get([FromBody]string rawjson)
{
}
I use Google Chrome Rest Console to try my methods first. I add my json content to RAW body and then send a get request.I put a breakpoint on my method to see if i can get the raw json data however, method invokes but rawjson comes as null. I've also tried put but that didn't work either.
What am i doing wrong ?
Thanks
GET methods cannot have Request Body and as such cannot parse values using [FromBody]. Please use the POST method.
Change the rawJson parameter type to Stream you will recieve anything that is posted on your service as as stream and than you can just read that stream to string
I must implement method in my application which will send some data (which according to api documentation should be JSON) using GET method (it is weird...). How I can do this using c sharp in windows 8 (RestSharp lib is not working there). I don't have any experience in REST clients but I have already implement other features but there data was sended by POST or DELETE methods. I have tried "tranlate" json to get like this:
JSON:
{
a = "foo",
b = "bar
}
GET URL:
__SITE__?a=foo&b=bar
But server return null values (not error). I don't know how to deal with this thing :/
Thanks for help in advance :)
If you have api you have name of param that you should send. Just convert the data into json and sind is as this param.
If you have to send json why you`re sending param a and b as 2 diffrent strings ?
remember that a GET method can be invoked by HttpClient. Just invoke the URL
Finally it turned out (in my case) that API also accepts providing data in that way: URL?a=foo&b=bar regardless of the fact that it should be json.
Long story short, I think this will be most illuminating .. it "fills in the blanks" with using HttpClient to fire JSON Formatted data at a REST API
How do you set the Content-Type header for an HttpClient request?