Parsing json_callback response from server Angular 4 - json

Using Angular 4, I sent a get request to this url https://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=JSON_CALLBACK&format=json&tagmode=all&tags=test
with following code,
this.http.get('https://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=JSON_CALLBACK', {
params: { format: 'json', tagmode: 'all', tags: query }
})
.subscribe(data => {
console.log(data);
});
The response I get is in the following format, wrapped as a method argument.
JSON_CALLBACK({
"title": "Recent Uploads tagged test",
"link": "https:\/\/www.flickr.com\/photos\/tags\/test\/",
"description": "",
"modified": "2018-02-04T14:51:42Z",
"generator": "https:\/\/www.flickr.com",
"items": [
{
"title": "Desktop2018-02-04-14_39_44.jpg",
"link": "https:\/\/www.flickr.com\/photos\/besnaveld\/28298869359\/",
"media": {"m":"https:\/\/farm5.staticflickr.com\/4769\/28298869359_e932760377_m.jpg"},
"date_taken": "2018-02-04T06:51:42-08:00",
"description": " <p><a href=\"https:\/\/www.flickr.com\/people\/besnaveld\/\">besnaveld<\/a> posted a photo:<\/p> <p><a href=\"https:\/\/www.flickr.com\/photos\/besnaveld\/28298869359\/\" title=\"Desktop2018-02-04-14_39_44.jpg\"><img src=\"https:\/\/farm5.staticflickr.com\/4769\/28298869359_e932760377_m.jpg\" width=\"240\" height=\"135\" alt=\"Desktop2018-02-04-14_39_44.jpg\" \/><\/a><\/p> ",
"published": "2018-02-04T14:51:42Z",
"author": "nobody#flickr.com (\"besnaveld\")",
"author_id": "154665852#N05",
"tags": "test booth"
} ]
})
How can I extract the data inside this JSON_CALLBACK function argument?

based on filckr document simply add
nojsoncallback=1 -> {...}
jsoncallback=wooYay -> wooYay({...});
to your request to get it right . then your url should be :
https://api.flickr.com/services/feeds/photos_public.gne?nojsoncallback=1&format=json&tagmode=all&tags=test

Related

Cypress login to REST endpoint is unauthorized, Postman works - upload of JSON file

We have a REST service with an incoming REST endpoint that accepts data. It has no web interface (Swagger or so), only the API. With Postman I can POST a JSON file (response code is 202) to it and then read the uploaded data from another endpoint.
When I want to log in to the same endpoint with Cypress to upload a JSON file from the fixtures folder (with the same body as in the Postman request), then I get response code 401 instead – Unauthorized. I have the feeling that the cypress request is wrong because the logfile of the service does not write a message when I use the cypress POST but it does when I use the Postman POST.
First question: What could I be doing wrong in the cypress request?
Second question: Once the authentication works, how can I POST/upload/push the content of the JSON file to that endpoint? Because I have no webpage to interact with, I cannot use click button functions. The documentation mainly deals with interpreting a JSON response but not with sending it.
My cypress code:
it('logs in to connector through REST API', () => {
cy.request({
method: 'POST',
url: 'localhost:8095/connector/demands/v1/demandData',
failOnStatusCode:false,
form: true,
body: {
Username: 'user',
Password: 'pass',
}
})
})
import my-request from '../fixtures/my-request.json'
it('loads the JSON file', () => {
cy.fixture('my-request.json')
})
The structure of the JSON file to upload is not too simple, here is a shortened version:
{
"#metadata": {
"context": "{{A}}"
},
"pool": "{{B}}",
"action": "NEW",
"Type": "ANNOUNCEMENT",
"ON": "Order123",
"PON": "PO123",
"SNN": "SN123",
"direction": "OUT",
"mode": 3,
"pack": [
{
"out": {
"outKey": "OUT14",
"outQuantity": "3",
"dimension": {
"length": "303",
"width": "33",
"height": "903",
"unit": "mm"
},
"layers": "3",
"weight": "3000",
"weightUnit": "grm",
"in": [
{
"inKey": "IN12",
"inQuantity": "3",
"article": {
"articleKey": "article3",
"quantity": "300",
"PON": "Art_PO300",
"SNN": "Art_SN300"
}
}
]
},
"p1": "pack3",
"p2": "pack4",
"store": true
},
{
"out": {
"outKey": "OUT23",
"outQuantity": "5",
"dimension": {
"length": "505",
"width": "55",
"height": "905",
"unit": "mm"
},
"layers": "5",
"weight": "5000",
"weightUnit": "grm",
"in": [
{
"inKey": "IN19",
"inQuantity": "5",
"article": {
"articleKey": "article5",
"quantity": "500",
"PON": "Art_PO500",
"SNN": "Art_SN500"
}
}
]
},
"p1": "pack5",
"p2": "pack5",
"store": true
}
]
}
Solution found. "form: true" must not be given because this overrides the content-type.
You can pass the contents of the fixture file(which is json) in the request body like this:
describe('Some Test Suite', function() {
// we can use these values to log in
const username = 'jane.lane'
const password = 'password123'
it('logs in to connector through REST API', () => {
cy.fixture('my-request.json').then(myFixture => {
cy.request({
method: 'POST',
url: 'localhost:8095/connector/demands/v1/demandData',
auth: {
username,
password,
},
failOnStatusCode: false,
form: true,
body: myFixture
})
})
})
})
For HTTP auth you have to use. You can check out this cypress recipe.
auth: {
username,
password,
}

writting a test suite in Postman

I am trying to run a test suit in post man by json file upload, and executing test cases by .xl file upload.
my test.json file look like below,
{
"info": {
"_postman_id": "af0ea50c-4264-41a6-ac2c-bcacbf966394",
"name": "CCAPI TEST",
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
},
"item": [
{
"name": "API TEST",
"event": [
{
"listen": "test",
"script": {
"id": "c195d434-6bb6-4c00-ae21-3d71552b86f0",
"exec": [
"let expected_response = pm.variables.get(\"expected_response\");\r",
"\r",
"console.log(\"expected_response:\"+expected_response + \" ->responseBody:\"+responseBody);\r",
"pm.test(\"Body matches string\", function () {\r",
" pm.expect(responseBody).to.include(expected_response);\r",
"}); "
],
"type": "text/javascript"
}
}
],
"request": {
"method": "POST",
"header": [
"Accept":"application/json",
"Content-Type":"application/json"
],
"body": {
"mode": "raw",
"raw": ""
},
"url": {
"raw": "{{ip_port}}/CCAPI/subscription",
"host": [
"{{ip_port}}"
],
"path": [
"CCAPI",
"subscription"
],
}
},
"response": []
}
]
}
In postman I am passing below data in body,
{
"name":"abc",
"number":"919876567876",
"value":"ENABLE"
}
POSTMAN RESPONSE:
{
"description":"successfully added",
"status":"success"
}
I want to pass the same to the json file, I am not getting where should I add this,
for result once the test is created after uploading the file, I click on run , there I will upload the .xl file, from there It has to check for the output of the api is matching or not
.xl file contents :
name number value expected_response
abc 988988999 ENABLE {"description":"successfully
added","status":"success"}
I am not getting where to add the body of the json REQ in the .json file
If anyone tried running test suite in postman tool who knows this reply

How to validate the contents inside the JSON body

In postman i want to to validate '"name": "Twilio"', which is inside data > twilio > viewable > name
here is the JSON response ive got
{
"success": true,
"timestamp": "2019-08-12T12:31:33+00:00",
"response_code": 200,
"data": {
"twilio": {
"name": "Twilio",
"slug": "twilio",
"image": "https://s3-eu-west-1.amazonaws.com/connector-assets/images/twilio.png",
"description": "Twilio is a cloud communications platform as a service. Integrate your Twilio account to send outgoing SMS from Purple.",
"category": "communication",
"connectedCount": 1,
"allowMultipleAdd": false,
"editable": [],
"viewable": {
"cf-5d51503868af3": {
"name": "Twilio"
}
},
"id": "cf-5d515c2527579",
"overrideAllowed": false
},
"salesforce-mc": {
"name": "Salesforce marketing cloud",
"slug": "salesforce-mc",
"image": "https://s3-eu-west-1.amazonaws.com/connector-assets/images/sf-mc.png",
"description": "Salesforce Marketing Cloud is a provider of digital marketing automation and analytics software and services.",
"category": "marketing-automation",
"connectedCount": 0,
"allowMultipleAdd": true,
"editable": [],
"viewable": [],
"id": "cf-5d515c252bc31",
"overrideAllowed": true
}
}
}
The easiest way is to process the response as JSON, and simply check your hierarchy:
In the tests section, you can add a number of tests:
pm.test("Response should be OK", function () {
pm.response.to.be.ok;
});
// You can actually check for explicit response code if a 200 series is not enough.
pm.test("Status code is 200", function () {
pm.response.to.have.status(200);
});
// Optionally test the returned Content-Type is correct.
pm.test("Content-Type is present", function () {
pm.response.to.have.header("Content-Type");
});
pm.test("Response should be okay to process", function () {
pm.response.to.be.ok;
pm.response.to.not.be.error;
});
pm.test("Body contains JSON data result with Twilio as the viewable name", function () {
const JsonData = pm.response.json();
pm.expect(JsonData.data.twilio.viewable.name).to.equal('Twilio');
});
For safety, you can check that each parent element exists first (validate data is in JsonData) to avoid errors should the payload change or not match what you expect.
EDIT: Your JSON structure:
{
"success": true,
"timestamp": "2019-08-12T12:31:33+00:00",
"response_code": 200,
"data": {
"twilio": {
"name": "Twilio",
"slug": "twilio",
"image": "https://s3-eu-west-1.amazonaws.com/connector-assets/images/twilio.png",
"description": "Twilio is a cloud communications platform as a service. Integrate your Twilio account to send outgoing SMS from Purple.",
"category": "communication",
"connectedCount": 1,
"allowMultipleAdd": false,
"editable": [],
"viewable": {
"cf-5d51503868af3": {
"name": "Twilio"
}
},
"id": "cf-5d515c2527579",
"overrideAllowed": false
},
"salesforce-mc": {
"name": "Salesforce marketing cloud",
"slug": "salesforce-mc",
"image": "https://s3-eu-west-1.amazonaws.com/connector-assets/images/sf-mc.png",
"description": "Salesforce Marketing Cloud is a provider of digital marketing automation and analytics software and services.",
"category": "marketing-automation",
"connectedCount": 0,
"allowMultipleAdd": true,
"editable": [],
"viewable": [],
"id": "cf-5d515c252bc31",
"overrideAllowed": true
}
}
}
Based on this, the text you are looking for is present, but under an ID, not directly available as you indicated. There are two checks that could be done:
1. Use the name in the main block
pm.test("Body contains JSON data result with Twilio as the viewable name", function () {
const JsonData = pm.response.json();
pm.expect(JsonData.data.twilio.name).to.equal('Twilio');
});
The other would be to extract the viewable value ('cf-5d51503868af3') and use this value as a key to do the test. Not sure if this is available to you from your user id or another data source. If not, then you need to extract it from the JsonData.data.twilio.viwable object. There are some more useful examples here in this answer.

how do i integrate authorize.net into my wix page?

I am using authorize.net's sandbox API to test their gateway in my wix (corvid/code) environment. Funny thing is that when i send JSON to the sandbox API i get a valid JSON response approving the (fake) transaction. however when i set it up thru wix i get data errors in my console. I have built on existing files that i have been able to run basic API responses, and more advanced auths with token responses. so the code works, just not with authorize.net. given my level of expertise, i think it might be something im doing wrong. i've done my due diligence, and there are no questions on this topic. here is my code:
///front end, from the corvid page's code
import {buyIt} from 'backend/authorizeNet';
export function button1_click(event) {
buyIt();
}
pretty basic, just calling code from my backend onClick. the filepath is correct. here is the module on the backend:
//// backend/authorizeNet.jsw
import {fetch} from 'wix-fetch';
export function buyIt() {
let data = {
"createTransactionRequest": {
"merchantAuthentication": {
"name": "***************",
"transactionKey": "****************"
},
"refId": "123456",
"transactionRequest": {
"transactionType": "authCaptureTransaction",
"amount": "5",
"payment": {
"creditCard": {
"cardNumber": "5424000000000015",
"expirationDate": "2020-12",
"cardCode": "999"
}
},
"lineItems": {
"lineItem": {
"itemId": "1",
"name": "vase",
"description": "Cannes logo",
"quantity": "18",
"unitPrice": "45.00"
}
},
"tax": {
"amount": "4.26",
"name": "level2 tax name",
"description": "level2 tax"
},
"duty": {
"amount": "8.55",
"name": "duty name",
"description": "duty description"
},
"shipping": {
"amount": "4.26",
"name": "level2 tax name",
"description": "level2 tax"
},
"poNumber": "456654",
"customer": {
"id": "99999456654"
},
"billTo": {
"firstName": "Ellen",
"lastName": "Johnson",
"company": "Souveniropolis",
"address": "14 Main Street",
"city": "Pecan Springs",
"state": "TX",
"zip": "44628",
"country": "USA"
},
"shipTo": {
"firstName": "China",
"lastName": "Bayles",
"company": "Thyme for Tea",
"address": "12 Main Street",
"city": "Pecan Springs",
"state": "TX",
"zip": "44628",
"country": "USA"
},
"customerIP": "192.168.1.1",
"transactionSettings": {
"setting": {
"settingName": "testRequest",
"settingValue": "false"
}
},
"userFields": {
"userField": [
{
"name": "MerchantDefinedFieldName1",
"value": "MerchantDefinedFieldValue1"
},
{
"name": "favorite_color",
"value": "blue"
}
]
}
}
}
}
return fetch("https://test.authorize.net/xml/v1/request.api", {
"method": "post",
"headers": {"Content-Type": "application/json"},
"body": data
})
.then(response => {console.log(response.json())});///if response.text is used, it gives details
}
note at the end of the backend code, calling response.json give me a json error, due to the return code contains HTML saying that i've requested invalid data. if i change it to response.text i get this in my console:
//console response with response.text
{...}
isFulfilled:
true
isRejected:
false
fulfillmentValue:
"<HTML><HEAD>\n<TITLE>Bad Request</TITLE>\n</HEAD><BODY>\n<H1>Bad Request</H1>\nYour browser sent a request that this server could not understand.<P>\nReference #7.1d60fea5.1557756725.387c74\n</BODY>\n</HTML>\n"
how do i get a good response from the API? like ive done with the same code in postman?
thanks in advance
return fetch(url, {
method: "post",
headers: {"Content-Type": "application/json"},
body: JSON.stringify(data)
})
.then(response => console.log(response.text())
)
this got me the result i was looking for
stringify() converted my object to a JSON string. i still cannot get it to read the incoming JSON, might have to use parse...but if i read as text i get the info i want and my API is showing a successful transaction.

MongoDB, NodeJS: updating an embedded document with new members

Using: MongoDB and native nodeJS mongoDB driver.
I'm trying to parse all the data from fb graph api, send it to my API and then save it to my DB.
PUT handling in my server:
//Update user's data
app.put('/api/users/:fbuser_id/:category', function(req, res) {
var body = JSON.stringify(req.body);
var rep = /"data":/;
body = body.replace(rep, '"' + req.params.category + '"' + ':');
req.body = JSON.parse(body);
db.fbusers.update({
id: req.params.fbuser_id
}, {
$set: req.body
}, {
safe: true,
multi: false
},
function(e, result) {
if (e) return next(e)
res.send((result === 1) ? {
msg: 'success'
} : {
msg: 'error'
})
});
});
I'm sending 25 elements at a time, and this code just overrides instead of updating the document.
Data I'm sending to the API:
{
"data": [
{
"category": "App page",
"name": "SoundCloud",
"id": "7919071058",
"created_time": "2013-09-16T18:16:59+0000"
},
{
...and so on
}
]
}
Basically my API changes "data" key from sent json to the category name, f.e.:
PUT to /api/users/000/likes will change the "data" key to "likes":
{
"likes": [
{
"category": "App page",
"name": "SoundCloud",
"id": "7919071058",
"created_time": "2013-09-16T18:16:59+0000"
},
{
...and so on
}
]
}
Then this JSON is put to the db.
Hierarchy in mongodb:
{
"_id": ObjectID("556584c8e908f0042836edce"),
"id": "0000000000000",
"email": "XXXX#gmail.com",
"first_name": "XXXXXXXX",
"gender": "male",
"last_name": "XXXXXXXXXX",
"link": "https://www.facebook.com/app_scoped_user_id/0000000000000/",
"locale": "en_US",
"name": "XXXXXXXXXX XXXXXXXXXX",
"timezone": 3,
"updated_time": "2015-05-26T18:11:59+0000",
"verified": true,
"likes": [
{
"category": "App page",
"name": "SoundCloud",
"id": "7919071058",
"created_time": "2013-09-16T18:16:59+0000"
},
{
"category": "App page",
"name": "SoundCloud",
"id": "7919071058",
"created_time": "2013-09-16T18:16:59+0000"
},
{
....and so on
}
]
}
So the problem is that my api overrides the field (in this case "likes") with newly sent data, instead of appending it to already existing data document.
I am pretty sure that I should be using other parameter than "$put" in the update, however, I have no idea which one and how to pass parameters to it programatically.
Use $push with the $each modifier to append multiple values to the array field.
var newLikes = [
{/* new item here */},
{/* new item here */},
{/* new item here */},
];
db.fbusers.update(
{ _id: req.params.fbuser_id },
{ $push: { likes: { $each: newLikes } } }
);
See also the $addToSet operator, it adds a value to an array unless the value is already present, in which case $addToSet does nothing to that array.