How to add parameters to a api? - javascript

I am trying to study wordpress REST api
If I do:
https://www.example.com/wp-json/wp/v2/categories
I get all categories.
But let's say I want to exclude a category, according to the documentation it says:
exclude
Ensure result set excludes specific IDs.
So I try
https://www.example.com/wp-json/wp/v2/categories?exclude=697
I still get all categories, am I using wrongly the parameters?
Should it be written like
https://www.example.com/wp-json/wp/v2/categories/exclude=697
or
https://www.example.com/wp-json/wp/v2/categories&exclude=697
Here it is the doc

The right way is
http://demo.wp-api.org/wp-json/wp/v2/categories?exclude=2,11
It's the ids separated by comma. I get the categories filtered. Category 697 doesn't seem to exist in the API example.
When you do a GET request, you send the parameters in the Query String. After the url, you end it with ? and the assign the value of the parameter like this: name_of_the_parameter=something. If you have multiple parameters, you concatenate them with &, For example:
http://example.com/some/page?name=ferret&color=purple

Related

How to create a facet filter that utilizes a prefix when filtering

I have an attribute that is of string data type.I am using the algoliasearchHelper object to search through my Algolia database. What I want to do is create a facet filter that takes a specified prefix and returns all objects that have a value with the specified prefix inside a specified attribute.
For example, so far I am using this:
Helper.addDisjunctiveFacetRefinement("attributeName","Can");
This returns all objects that have the value of "Can" in the "attributeName" attribute, but it doesn't return any objects that have the value of "Canada" or "Canadians" in the "attributeName" attribute, even though those have a prefix of "Can".
How can I make it so that when it filters, it filters with a specified prefix.
A disjunctive facet refinement is used for an exact match of a filter. This is mainly used to select a certain filter out of a list of possible filters. What I assume you want, is to get a subset of all possible filters.
This is possible with our searchForFacetValues function. First this needs to be set up in your indexing settings as searchable(attributeName) so we can generate the additional data structures to make the facets easily searchable. You can also read more about that setup in the documentation.
So once the attribute is searchable, you can use the helper function to refine the list of filters like this:
Helper.searchForFacetValues("attributeName","Can");
Have a great day!

How to properly send URL parameters containing commas using AngularJS?

I have a feeling I am just looking at this wrong, but I want to get feedback on the proper way to pass URL query parameters through Angular's $http.get() method - specifically, parameters that contain commas.
Let's say I have the following data, to be used as URL parameters in a GET request:
var params = {
filter : [
"My filter",
"My other filter",
"A filter, that contains, some commas"
],
sort : [
"ascending"
]
};
Now, I convert this structure to some parameters that can be fed into $http.get:
var urlParams = {};
angular.forEach(params, function(value, name) {
urlParams[name] = "";
for (var i = 0; i < value.length; i++) {
urlParams[name] += value[i];
if (i < value.length - 1) {
urlParams[name] += ","
}
}
}
At this point, urlParams looks like this:
{
filter : "My filter,My other filter,A filter, that contains, some commas",
sort : "ascending"
}
Now, that isn't what I want, since the third filter parameter has now turned into three separate parameters. (The API I am working with does not allow multiple values for a parameter to be passed in any other way than: "?param=value1,value2,value3") So, what I need to do is URI encode these values first, right? So, I add a encodeURIComponent() to the above routine like this:
urlParams[name] += encodeURIComponent(value[i]);
This gives me a parameters object that looks like this:
{
filter : "My%20filter,My%20other%20filter,A%20filter%2C%20that%20contains%2C%20some%20commas",
sort : "ascending"
}
Now, I make a request:
var config = {
params : urlParams
};
$http.get("/foo", config).then(function(response){
console.log(response);
});
... and this doesn't work, since Angular encodes the URL parameters as well, so the request ends up looking like this:
GET "/foo?filter=My%2520filter,My%2520other%2520filter,A%2520filter%2C%20that%20contains%2C%20some%20commas&sort=ascending"
As you can see the parameters are being encoded twice (the % signs are being encoded as %25), which of course, won't work.
Obviously, I am doing it wrong. But what is the right way? Or, do I need to ask the API developer to accept URL parameters like this?
GET "/foo?filter=My+filter,+with+a+comma&filter=Another+filter"
where multiple parameter values are stated separately, instead of being comma delimited?
As you've described the API, there is no way to reliably pass values containing commas.
Suppose you want to pass the items ["one","two","three,four"] as a list.
If you pass the strings as-is, the API will see (after the normal server-side URL decoding)
one,two,three,four
which makes the three,four indistinguishable from two separate items.
If you pass the strings URL-encoded, the entire parameter will be double-encoded, and the API will see (again, after URL decoding)
one,two,three%2Cfour
Now the parameters are distinguishable, but this requires support from the API to URL-decode each item separately.
Suppose you pass the strings like one,two,"three,four", i.e. items containing commas are quoted. The API can decode the parameters correctly, but it needs to support a more complex syntax (quoted strings) instead of simply splitting by commas...
...and so on. The bottom line is that without additional support from the API, I don't think there is anything you can do client-side to trick it into decoding strings containing commas correctly. There are many tweaks that the API developer can make, e.g.
Accepting some escape sequence for commas within list items which is unescaped server-side.
Accepting each item in a separate URL parameter.
Accepting JSON-encoded body via POST.
You will need to ask the API developer to do something.
I think you shouldn't have used comma as delimiter of the array.
I would recommend to
send json data using POST (which requires API change)
or use another string as delimiter. For example, ###.
FYI, you can simply join your array into string like this.
array.join(',')
From $http docs
If you wish override the request/response transformations only for a single request then provide transformRequest and/or transformResponse properties on the configuration object passed into $http.
Note that if you provide these properties on the config object the default transformations will be overwritten. If you wish to augment the default transformations then you must include them in your local transformation array.
In short you can use your encodeURIComponent() functionality to replace the default one by including transformRequest property in the config object for each request or you can establish a global override
See "Transforming Requests and Responses" in $http docs for more details
Not sure why you want to send this as GET in the first place

Sails.js - Have a 'contains' or query in url to fetch appropriate JSON data

My Sails.js application has a model called 'Ideas' and using the default blueprint REST api, I can access the contents of the collection when I go to: http://example.com/ideas/find
Furthermore, by default, I can also limit the data to get specific titles: http://example.com/ideas/find?title=How to Watch TV
Although what I want to do is display the JSON data of ALL titles that contain the keyword 'T' but when I replace the above with the likes of
a) ?title=TV
b) ?q=TV
c) ?query=TV
d) ?where(title : (contains:'TV')
none of them work
How can I get JSON output that contains all titles that contains a particular keyword?
Based on the documentation, the where example should work. It uses curly brackets instead of parenthesis though.
?where={"title":{"contains":"TV"}}
For multiple use ",".
Example :
ideas/find?where={"title":{"contains":"music"}},{"title":{"contains":"film"}}

Ruby & Rails - Convert String to Proc

I'm in the following situation. The current url looks like the following:
/categories/Art
And I'm using name = location.pathname.split('/')[2] in order to grab the Art portion of the URL. Then, I send an AJAX the following path back to the controller: http://localhost:3000/sort?sortMethod=name&category=name or date, whichever link is clicked on.
Now in my controller I can use sort = params[:category] to get the string name, yet what I'd like to do with this string is sort an array by it. #categories is an array of objects and I'd like to call .sort_by(&:sort) yet it doesn't recognize the string value of sort = name. So now I'd like to convert this string into a proc in order to sort the array. Anyone know how I accomplish this?
Any help is greatly appreciated!
Convert it to a symbol first and then use Symbol#to_proc:
#categories.sort_by(&sort.to_sym)
However be sure that the users can't call anything malicious on your objects like:
http://localhost:3000/sort?sortMethod=destroy
One way of protecting yourself is to use attribute_accessible definitions in your model and then do
#categories.sort_by(&sort.to_sym) if Category.accessible_attributes.include? sort.to_sym
The problem is not entirely clear, so you may need to adjust the following solution. However, the basic idea is taht it's possible to do something like:
Category.all.sort_by {|category| category.method(params[:category]).call }
Also, the "Art" portion of your url is available in Rails' params hash as params[:action], so you don't have to do location.pathname.split('/')[2].

DOJO: Adding multiple conditions for querying dojox.grid.DataGrid

I'm trying to create a DOJO DataGrid populated using a dojo.data.ItemFileReadStore with very simple json data which has an ID and a description.
When an event occurs, i need to filter the rows displayed based on the IDs.
When its a single ID, i can fix it by just adding myGrid.setQuery({ID:"someIdIWant"});
Is there some way i can filter more than 1 ID in the same piece of codde? For ex i want to filter ID1 and ID2 to be shown.
I do not have a REST url exposed, my data is populated as javascript variables.
Can i still JsonQueryRestStore using just json data in JS vars or dojo.data.ItemFileReadStore?
The dojo.data.ItemFileReadStore supports using regular expressions in the query. The code internal to the ItemFileReadStore uses dojo.data.util.filter.patternToRegExp() to identify whether or not the string value in your query could be parsed as a regular expression. However, to be more precise, you can pass a RegExp object in your query. The two options look like this:
myGrid.setQuery({ID:"123|124"});
// or
myGrid.setQuery({ID: new RegExp("123|124")});
Both examples fetch the two items with ID "123" and "124" respectively.

Categories