Need one help regarding fetching data value from response - rest

Need one help regarding fetching data value from response.
Below is my response which I got after hitting URL.
{
"response": {
"Error Message": "Invalid Input missing",
"success": "false""
}
}
In this I want to read "Error Message" through POSTMAN test. For same reason I have written below code, but it is not working due to space between key.
var data = JSON.parse(responseBody);
tests ["Verify Error message"] = data.response.Error Message==="Invalid Input - Mandatory data(Company ID/source Id/SalesRep Ids/ContactPerson Ids) missing";

You're trying to use Error Message as a field with a space in it. Try:
tests ["Verify Error message"] = data.response.["Error Message"]==="Invalid Input - Mandatory data(Company ID/source Id/SalesRep Ids/ContactPerson Ids) missing";

This is not good to compare string.
In your response you must have like this,
{
"response": {
"Error Message": "Invalid Input missing",
"success": "false",
"responseCode" : 400
}
}
for more response codes, please go to this link,
http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
Then after do comparison,
var data = JSON.parse(responseBody);
if(data.reponse.responseCode == '400'){
// do stuff
}

Related

Getting 'expected { Object (message, detail) } to have property 'count' error in API testing using cypress

I want to assert the total count received from the response.
This is my code:
cy.request({
method:'GET',
url:'https://ibis-qa.droicelabs.us/api/practice/orders/?q=&limit=100',
failOnStatusCode: false,
headers:{
accept: "application/json"
}
}).then(Response => {
let body = JSON.parse(JSON.stringify(Response.body))
cy.log(body)
expect(body).has.property('count','27')
})
and this is the error that I have got
Please use
expect(body).has.property('count', 27)
as the value is a number
(see screen-shot, there are no quotes around 27)
You are not getting the JSON response you think you should have.
If go to the URL in the browser, I get this
{"message":"field required","detail":[{"loc":["header","authorization"],"msg":"field required","type":"value_error.missing"}]}
which is what is partially shown in the screenshot of the error message.
This is an error response from the server, and it means your request is not correct.
Then you can directly use the assertion like this. You don't need to parse or stringify.
expect(Response.body).to.have.property('count',27)
You can check this example from the cypress docs.

JSONError | No data, empty input at 1:1

I'm tring to print the response code in the console, but i always end up in getting the response as "JSONError | No data, empty input at 1:1"
im getting this error when the response code is 204. else condition works fine.
script is not entering to the condition.
please review the code and provide a solution. Thanks.
var respcode=pm.response.code;
var stagresbody=pm.response.json(responseBody);
if (respcode === 204) {
pm.test("engine is suspended with resposne code"+respcode,function(){
console.log(respcode);
})
}
else { pm.test("Staging is resumed with message"+stagresbody.serviceStatus,function(){
console.log("Staging is resumed with message "+stagresbody.serviceStatus);
});
}
You could use this to do the same thing:
if (pm.response.code === 204) {
pm.test(`Engine is suspended with resposne code ${pm.response.code}`, () => {
console.log(pm.response.code);
})
}
else {
pm.test(`Staging is resumed with message ${pm.response.json().stagresbody.serviceStatus}`, () => {
console.log(`Staging is resumed with message ${pm.response.json().stagresbody.serviceStatus}`);
});
}
My Postman Test has console log for json response. But my request would not give any response ( i.e. response body is blank ) and thereby giving "No data, empty input at 1:1" error.
I resolved this problem by commenting logging of response.
pm.test("Status code is 200", function () {
pm.response.to.have.status(204);
});
// Below line would give me error "JSONError | No data, empty input at
//1:1" as my request won't output ant response i.e. response body is blank.
// Commenting this line resolve problem.
*//console.log( pm.response.json()[0].name);*

API V1 RESTful. I got "Unknown error" when added line break to JSON. Is it OK?

I'm testing API queries and sending POST with such body:
{
"books": "12",
"available": "true",
"id": "qwe2323-2342rfws-23r2rfew"
}
I got 200 response - OK.
But when I add line break to one of the string data, e.g.:
{
"books": "12",
"available": "true",
"id": "qwe2323-2342rfws-23r
2rfew"
}
I got 500 "Unknown error".
My question: Can the server recognize this error and return a response, for example, WRONG_ID? In fact, I just added a line break character to the identifier string. In theory, the script should see the forbidden symbol without problems and return the corresponding error. Can I give such a recommendation to fix this error?
The payload is INVALID which generates an exception at the server and responded with 500 as it cannot understand the data payload.
To check the payload and show a INVALID JSON DATA or through any custom message, you can check the payload on every POST request at the server side, as in below example for PHP programming language:
private function handleRequest(Request $request, Programmer $programmer)
{
// ...
if ($data === null) {
throw new \Exception(sprintf('Invalid JSON: '.$request->getContent());
}
// ...
}
Reference:
https://knpuniversity.com/screencast/rest/error-invalid-json#handling-invalid-json

Angular 2 how to read Custom error message from backend

My problem with Angular 2 that was not exist in AngularJS, that I was sending the error message as a string with backend API call in case I have error, with error status 401 as example, the problem now that I can't read this message from Angular2 http response message, while I can do that from AngularJS:
I tried the following codes and nothing was helpful:
Promise:
this._http.post('/login',{email: 'email#example.com', password: '123'})
.toPromise()
.then((resp) => console.log(resp), (error) => console.log(error));
Observable:
this._http.post('/login',{email: 'email#example.com', password: '123'})
.subscribe(response =>console.log(response), (error) => console.log(error));
And from back-end I send response as a text, for OK or Unauthorized, for OK i send back String token == UUID.randomUUID().toString();, for error I send back message like String error = " Invalid credentials ";, the problem is that the console.log works and print the text for success (token in this case), but in case error, its just prints: Response with status: 200 for URL: null.
If I change code to JSON.stringify(error) I get something like this:
{"_body":{},"status":401,"ok":false,"statusText":"Unauthorized","headers":{"null":["HTTP/1.1 401 Unauthorized"],"Access-Control-Allow-Headers":["Origin"," X-Requested-With"," Content-Type"," Accept"," Referer"," User-Agent"],"Access-Control-Allow-Met
hods":["POST"," GET"," PUT"," DELETE"," OPTIONS"],"Access-Control-Allow-Origin":["*"],"Allow":["*"],"Content-Length":["36"],"Content-Type":["text/plain; charset=utf-8"],"Date":["Tue"," 23 Aug 2016 14:53:25 GMT"]},"type":2,"url":null}
As you can see the error test not even mentioned inside the Object !!
I tried to change the response for error from backend to return json like this:
{
"message": "invalid email or password"
}
I can get the result inside _body, and I can only read it like this: console.log(error._body.message) ! but i feel its something wrong this way, and I don't want to response as a json in this case.
For angularjs (angular 1), its so simple just to print the response and everything is cool, while in angular 2 its a really problem.
What the problem, and how I can solve this issue without any refactor to backend?
Edit:
I'm using Angular 2.0.0-rc.4 and same for http : `"#angular/http": "2.0.0-rc.4"
Mothanfar
In my case I'm working with the Asp Web Api as back end,this thing is making me crazy as well, the only solution I found is transform in a json and read the message, I know is really ugly but works for me.
Regards.
CheckError(error: any) {
let servermsg: any = JSON.parse(error._body)["ModelState"]["Login"][0];
if (servermsg) {
this.showMsg = true;
this.msg = servermsg;
}
}
If you are returning JSON object from the server, you may use the below code at client side:
let errMsg: ErrorMessage = err.json();
console.log(errMsg.message)
export class ErrorMessage {
message:string;
}

facebook Access Token 400 bad request

I am using following code to retrieve facebook accessToken
string url = "https://graph.facebook.com/oauth/access_token?" +
"client_id={0}" +
"&redirect_uri={1}" +
"&client_secret={2}" +
"&code={3}";
url = string.Format(url, clientId, redirectUri.EncodeUrl(), clientSecret, code);
//Create a webrequest to perform the request against the Uri
WebRequest request = WebRequest.Create(url);
try
{
//read out the response as a utf-8 encoding and parse out the access_token
using (WebResponse response = request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
//string urlRedirects = response.ResponseUri.ToString();
Encoding encode = Encoding.GetEncoding("utf-8");
if (stream != null)
{
StreamReader streamReader = new StreamReader(stream, encode);
string accessToken = streamReader.ReadToEnd().Replace("access_token=", "");
streamReader.Close();
response.Close();
return accessToken;
}
}
}
}
catch
{
return null;
}
however I am constantly receiving this ambiguous error message
{
"error": {
"message": "Error validating verification code.",
"type": "OAuthException",
"code": 100
}
}
I checked the code 100 "Invalid parameter" doesn't means much to me at all.
anyone have had similar problem?
Check you are adding correct code in the url
For example
http://www.xyz.com/?code=AQC399oXame3UKmoAMYnqkZOEXPDNa8ZUFEY9sc6I4YNQnNT-ZgHzpMNnQVZrCUBZVqJRIB1QrXC5xW58_8MNIgQol_PaQvYssUM8OiKjSY5aoqGLBMuCeeHsSqP_mRTd1xiK0iretZcXwMm_27lFYrWFw345Mxod_lfJuB8zI13E8wJUQiArXW_ZlGLNcyxh20#_=_
Code must be
code = AQC399oXame3UKmoAMYnqkZOEXPDNa8ZUFEY9sc6I4YNQnNT-ZgHzpMNnQVZrCUBZVqJRIB1QrXC5xW58_8MNIgQol_PaQvYssUM8OiKjSY5aoqGLBMuCeeHsSqP_mRTd1xiK0iretZcXwMm_27lFYrWFw345Mxod_lfJuB8zI13E8wJUQiArXW_ZlGLNcyxh20
code should not include following in the end
#_=_
If above did not solve the problem
2. redirect_uri must end with /
redirect_uri=http://www.xyz.com/
The following gives some times above mentioned error
redirect_uri=http://www.xyz.com
3. A lso make sure
App on Facebook and Website with Facebook Login are set with same addresss
e.g http://www.xyz.com/
You need to send the user to the Facebook Login page to get a valid code. The code should then be used to get the access_token for the user.
Follow the Authentication Guide.
I also got error message 400, when my app id and secret were wrong (i had messed up develop and production id-s and secrets).
Fixing them (watch also out for the correct host) fixed this problem for me.