ShopStyle API - How to Invoke an HTTP request - api

How do I Invoke an HTTP request with a particular URL and process the body of the response as XML?
Information Provided by ShopStyle:
HOW TO USE THE API:
Choose the method that returns the data your application needs. For example, the /products method is used to get products that match a given category or brand.Construct a URL for that method with the appropriate host, method name, and query parameters. Invoke the URL as an HTTP GET.
When the HTTP response arrives, extract the required data elements from the response's body.The rest of this document describes the details of constructing the right URL for each of the API methods. The XML format of the responses may be seen by clicking on the sample URLs shown for each method. The responses in JSON format contain identical information, just in a different format.
SHOPSTYLE API URLS
All ShopStyle API URLs have the following form:
http://api.shopstyle.com/api/VERSION/METHOD_NAMEpid=YOUR_API_KEY&format=FORMAT&...
The METHOD_NAME is taken from the list of methods in the various API shown at left (Press Link To View List of Methods-https://www.shopstylecollective.com/api/overview).
COMMON API PARAMETERS
All methods in the API accept these parameters:
API_KEY (my unique key is ******************)
pid Unique API_KEY string that is assigned to the caller. You can find your API Key on the Account Settings page.
FORMAT
The format of the response. Supported values are:
json - The response is in JSON format with UTF-8 encoding. This is the default if the parameter is absent.
xml - The response is in XML format with UTF-8 encoding.
jsonp - The response is in JSON format with UTF-8 encoding wrapped in a JavaScript method called padding. The padding must be specified with the query parameter 'callback'. Only single expressions (function reference, or object property function reference) are accepted as valid padding.
When set to 1 or 'true' the HTTP status will always be 200. Use the field "errorCode" in the response to detect whether the API Call was successful. By default, when an error occur the HTTP Status of the response will be different than 200
Again I am a beginner, so please provide detailed information on how to retrieve CATEGORY data (Examples: Dresses, Tops, Buttoms, etc) in XML format.**
Thank you!!!

Here's a simple example to get your started. Copy the code below and put it into a file, say "cat.php". Then run it by typing "php cat.php" at a command prompt (assumes you have php on your machine):
<?php
// don't show dom parse errors
libxml_use_internal_errors(true);
// grab the xml from the api
$response = file_get_contents("http://api.shopstyle.com/api/v2/categories?pid=TEST&format=xml");
$doc = new DOMDocument();
$doc->loadHTML($response);
// grab all the categories
$elements = $doc->getElementsByTagName('categories');
foreach($elements as $node){
foreach($node->childNodes as $child) {
// get the name out of the category
$nodes = $child->getElementsByTagName("name");
foreach ($nodes as $name) {
echo $name->nodeValue . PHP_EOL;
}
}
}

Related

Google Sheet API batchUpdateByDataFilter PHP Function

https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchUpdateByDataFilter
We have used above function in our code, while we are passing the more than 50 or 100 records within the array records then given 400 bad request array in response.
Can anyone describe the limit of the total values that we are going to pass within the above function?
Here is my code:
$batchupdate = array("valueInputOption" => "RAW", "data" => $dataarray);
try {
$requestBody = new Google_Service_Sheets_BatchUpdateValuesByDataFilterRequest($batchupdate);
$response = $service->spreadsheets_values->BatchUpdateByDataFilter($spreadsheetId, $requestBody);
}
catch(Exception $e) {
echo 'Message: ' . $e->getMessage();
}
Troubleshooting:
Problems with the Request
Until you attach a sanitized version of your Request body we cannot be sure about the root-cause of the problem you are facing.
However, an error 400 means that the request you did is invalid. So, most likely, the problem is in that.
Check if your request object is formatted as detailed on the documentation.
Problems with the Client
If you are able to use the Try this API sidebar with the same Request Body then it could be related to the PHP client.
Note: This is language independent. Create a JSON Object that has the same structure as your request body.
If that's the case, we will need to see more of your code to verify that you are not using your valid Request body in an invalid way (eg. sending it encapsulated in another object).
By referencing the PHP Library documentation you can see the properties of the objects you can use.

Call to java script code returning the ASCII encoding for ':' separating key and value of returned object

I making an api request using karate where one of the api request params takes a filter condition (which is a java script object).
I am using a literal notation to create a java script object as shown below. This code is in a separate filter.js file.
function() {
var params = {
val1:[],
val2:[]
};
return params;
}
Now i call the above .js file in the karate scenario as below:
Scenario: Test
Given path 'filtertest/'
* param filter = call read('classpath:feature/common/filter/filter.js')
When method get
Ran the above and when i check the log, the api throws bad request error. I looked at the request url and there i can see that the ':' in the js file where I am assigning a value to a object key is replaced with %3A which i believe is the ASCII encoding for ':'. (the param with its values below)
?filter=%7B%22val1%22%3A%5B%5D%2C%22val2%22%3A%5B%5D
What I want is the ':' to come as it is from the .js call as the server side expects the filter param values as key value pairs.
Is there a way I can achieve this?
If your server cannot decode an encoded : it is a bug: https://www.w3schools.com/tags/ref_urlencode.asp
If you really need this - the workaround is to use the url keyword and build it manually, path and param will always encode.
Given url baseUrl + '/filtertest?filter=foo:bar'

Extract report results with CloudConnect

I would like to extract raw report results within the CloudConnect process.
So far I have managed to get response from the raw report API end point - https://secure.gooddata.com/gdc/app/projects/{project_id}/execute/raw/
This response contains URI to the file and if I put that URI to browser, file is uploaded.
I have tried passing this URI to the following readers without success:
CSV Reader produces the following error:
------------------- Error details ------------------
Component [CSV Reader:CSV_READER] finished with status ERROR.
Parsing error: Unexpected end of file in record 1, field 1 ("date"),
metadata "outOfStock";
value: Raw record data is not available, please turn on verbose mode.
File Download - I don't know how to pass the URI through the port to "URL to Downlaod" parameter.
HTTP Connector again I don't see how to pass URI from the port.
What is the way to do this?
EDIT
If I use the HTTP Connector as suggested by #Filip, I get the following error:
Error details:
Component [HTTP connector:HTTP_CONNECTOR] finished with status ERROR. hostname in
certificate didn't match: xxx.com != secure.gooddata.com OR secure.gooddata.com
I have tried setting header to X-GDC-CHECK-DOMAIN: false with no effect.
The HTTP connector is the right component to go with. Leave the URL property empty and use the component’s property called “Input mapping”, where in the graphic editor you can assign the input edge field to the URL field.
Solution from GoodData support:
HTTP connector can be also used, but it is very complex, because
logging in to GoodData has to be created. REST connector has it built
in.
If you want to run the example graph, you have to be logged in in
CloudConnect with a user who has access to the project from where you
would like to export the report. You also have to change URL to
the one of white-labeled account in both REST connector components and change project
and report definition in the first REST connector.
So the graph that works looks like this:
Here are the main fields that you will need to set for each element:
Get Results URI - set params for POST request:
Request URL = https://secure.gooddata.com/gdc/app/projects/${GDC_PROJECT_ID}/execute/raw/
Request Body =
{
"report_req": {
"reportDefinition": "gdc/md/${GDC_PROJECT_ID}/obj/${OBJECT_ID}"
}
}
Get URI from Response - just map uri value to corresponding field:
<Mapping cloverField="uri" xpath="uri"/>
Load Results - make sure it is connected to metadata with two fields, one for response with data, other to pass through the uri.
Load Results - you will need to exclude uri field to process the data:
Exclude Fields = uri

Use URL as an API method for Slackbot in Express js

I am still new to javascript and trying to write a Slackbot in express js. I want to use the method defined in https://api.slack.com/methods/channels.history. How should this look syntacticly and how do I use it since the method is simply a URL?
You need to make an http request for the URL and you'll be returned a response with an object containing the status (ok:true|false), if there are more messages (has_more:true|false), and then an array of the actual messages (messages:array).
The response should look something like this:
{
has_more:true
messages:Array[100]
ok:true
}
The url that you make the get request to should look something like:
https://slack.com/api/channels.history?token=BOT_TOKEN&channel=CHANNEL_ID&pretty=1
Where BOT_TOKEN is the token attached to the bot you created, and CHANNEL_ID is the ID (not the name) of the channel whos history you want to get (9 uppercase alphanumeric characters, starts with a "C").
There are also a few other parameters you can include in the url. For example, "latest=", "oldest=", "inclusive=", "count=", and "unreads=". Details about those parameters can be found on the page you linked to (https://api.slack.com/methods/channels.history).
If you want to test it out in your browser's console, find a page where jQuery is loaded, open your dev tools and head into the console, and enter the following (with your bot token and channel id swapped in):
$.get('https://slack.com/api/channels.history?token=BOT_TOKEN&channel=CHANNEL_ID&pretty=1', function(response){console.log(response)});

Calling a webservice using google closures jsonp and sending json as parameter

I want to call a webservice using google closures, via jsonp since i am performing a cross domain webservice.
And i am calling it in the following manner
var url = "http://myurl/";
var jsonp = new goog.net.Jsonp(url);
jsonp.send(
{"name":"jessi","action":"initaction","gameId":"123"},
callback, callbackfailed);
But in this method the url is converted as a normal get method string as the follows
http://myurl/?name=jessi&action=initaction&gameId=123
But i need to send this url as a json object in the following manner
"name":"pari123","action":"initaction","gameId":"slotreel3"
How can i do this, i searched google and i couldnt find proper documentation regarding ?this.
The function goog.net.Jsonp.addPayloadToUri_ that is used to encode the object says:
#param {!Object} payload A map of value name pairs to be encoded.
A value may be specified as an array, in which case a query parameter
will be created for each value, e.g.:
{"foo": [1,2]} will encode to "foo=1&foo=2".
This is exactly what is happening. So, why not initialize your url with the query? e.g.
var url = "http://myurl.php?" + goog.json.serialize({"name":"jessi","action":"initaction","gameId":"123"});
var jsonp = new goog.net.Jsonp(url);
jsonp.send()
Untested but maybe this works.
Regards,
Rene