Axios request to Opensearch/Elasticsearch - javascript

Currently able to GET and POST to my collection but need the ability for more complicated queries, I am using bodybuilder to structure the request and axios as my client.
However using POST doesn't return my specified results instead just the first 10 items in my index and using GET I'm unable to send a body for these complicated requests leaving me with POST.
I've switched setting my data from data:data to body:data with the same result.
Currently this is my POST which again returns data but NOT my filtered data just the first 10 items of my collection.
Any insight would be appreciated!
export function searchQuery(search: string) {
var body = bodybuilder().query("query_string", "query", search).build();
const data = JSON.stringify(body);
axios({
url: `${SEARCH_URL}`,
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: data,
}).then((res) => {
console.log(res);
});
}
This is my current log of data:
{"query":{"query_string":{"query":"Green"}}}

Based on the comments in the question above, you are getting only the first 10 items in your collection, when you run the query against elasticsearch directly.
This is because elasticsearch by default returns only 10 documents in the search result if no size param is included in the search query.
If you want to get more than 10 results, you need to modify your search query as
{
"size": 20, // change this according to your requirement
"query": {
"query_string": {
"query": "Green"
}
}
}

Related

No response from API

I have created an API call in excel to get data from a Wix database.
The call:
Dim http As Object, JSON As Object
Set http = CreateObject("MSXML2.XMLHTTP")
http.Open "GET", "https://username.wixsite.com/mysite/_functions/Functionname", False
http.setRequestHeader "Authorization", "myauthkey"
http.Send
MsgBox (http.responseText)
The javascript http backend file on Wix:
import { ok, notFound, serverError } from 'wix-http-functions';
import wixData from 'wixdata';
export function get_Wixdata() {
let options = {
"headers": {
"content-type": "application/json"
}
};
return wixData.query("wix data collection name")
.find()
.then(results => {
if (results.items.length > 0) {
options.body ={
"items": results.items
}
return ok(options);
}
})
}
I tested the call (without authorisation) on JSON place holder and it worked fine.
Just trying to debug what's happening as I am getting "" as a response.
Even if I enter the wrong API key I still get "", even a wrong url it's still a "" response.
I take it I am clearly way off the mark with what I am trying to do..
Did you tried put both headers in your request, like the following:
let headers = new Headers({
'Content-Type': 'application/json',
'Authorization': '....'
});
The issue was with the VBA call, the header was not needed.
Dim https As Object, JSON As Object
Set https = CreateObject("MSXML2.XMLHTTP")
With CreateObject("Microsoft.XMLHTTP")
.Open "GET", "end point url", False
.send
response = .responseText
End With

Axios Percent Encode on GET request

I'm trying to make a GET request in Axios with what I believe are "percent encoded" parameters. D
I am trying to call a URL that should resolve to:
https://example.com/api/list?pageSize=15&statusFilters=%5B"DELETED"%2C"DRAFT"%5D
Below is my code, however this resolves to https://example.com/api/list?pageSize=15&statusFilters[]=LIVE&statusFilters[]=DRAFT which for some bonkers reason returns a completely different set of results (not my API)
var params = {
pageSize: 15,
statusFilters: ["LIVE","DRAFT"]
}
return axios({
method: 'GET',
params,
url: `${API_URL}${url}`,
})

JSON-Server doesn't update my .json file after fetching some new data

Currently I'm working on little app that's using JSON server but I have a little problem. Objects I'm working with consist of id, name, and complete fields like this {"id": ,"name": ,"complete": }. Fetching data from the server works fine but putting some new data inside it doesn't work. My code looks like this:
export const addNewItem = (newItem) =>{
return fetch(myUrl, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type':'application-json'
},
body: JSON.stringify(newItem)
}).then(res => res.json())
}
After adding new item to my server there only id in it ({"id": some new id}. The name and complete fields are gone. Where am I making mistake?

Can Mockjax handle single IDs Api from Json file

I'm using Mockjax for the first time to mock a Restful API which will return a series of data given an id. Right now i have a json file that has several Items, and i would like to have a function inside Mockjax (or where necessary) to return only the queried ID. how can I achieve this?
current code :
$.mockjax({
url: "/Api/Cases/{caseId}",
proxy: "/mocks/cases nuevo.json",
dataType: 'json',
responseTime: [500, 800]
});
$.ajax({
type: 'GET',
url: '/Api/Cases/',
data: {caseId: taskId},
success: function(data){
//use the returned
console.log(data);
}
});
current error:
GET http://localhost:8080/Api/Cases/?caseId=100 404 (Not Found)
Great question... yes, you can do this. But you'll have to write the functionality yourself using the response callback function and then making a "real" Ajax request for the file (instead of using the proxy option). Below I just make another $.ajax() call and since I have no mock handler setup for that endpoint, Mockjax lets it go through.
Note that setting up URL params is a little different than you suggest, here is what the mock setup looks like:
$.mockjax({
url: /\/Api\/Cases\/(\d+)/, // notice the regex here to allow for any ID
urlParams: ['caseID'], // This defines the first matching group as "caseID"
responseTime: [500, 800],
response: function(settings, mockDone) {
// hold onto the mock response object
var respObj = this;
// get the mock data file
$.ajax({
url: 'mocks/test-data.json',
success: function(data) {
respObj.status = 200;
// We can now use "caseID" off of the mock settings.urlParams object
respObj.responseText = data[settings.urlParams.caseID];
mockDone();
},
error: function() {
respObj.status = 500;
respObj.responseText = 'Error retrieving mock data';
mockDone();
}
});
}
});
There is one other problem with your code however, your Ajax call does not add the ID to the URL, it adds it to the query string. If you want to use that API endpoint you'll need to change your source code $.ajax() call as well. Here is the new Ajax call:
$.ajax({
type: 'GET',
url: '/Api/Cases/' + taskId, // this will add the ID to the URL
// data: {caseId: taskId}, // this adds the data to the query string
success: function(data){
//use the returned
console.log(data);
}
});
Note that this presumes the mock data is something like:
{
"13": { "name": "Jordan", "level": 21, "id": 13 },
"27": { "name": "Random Guy", "level": 20, "id": 27 }
}
What I have ended up doing, is: I have left the $.mockjax function untouched, and i have manipulated the data inside the ajax request, using jquery's $.grep function as follows:
$.ajax({
type: 'GET',
url: '/Api/Cases/' + taskId,
success: function(data){
//note you have to parse the data as it is received as string
data = JSON.parse(data);
var result = $.grep(data, function(e){ return e.caseId == taskId; });
//since i'm expecting only one result, i pull out the result on the 0 index position
requestedData = result[0];
}
});
The $.grep() method removes items from an array as necessary so that all remaining items pass a provided test see Jquery API, And since our test is that the caseId attribute of the element equals to the taksId variable sent, it will return all the elements that match the given Id, in this case, only one, this is why I've taken only the result on the 0 index position requestedData = result[0];
**Note: **
A more suited solution would be a mixture between what i've done and #jakerella 's answer, since their method implements the find element method inside the mockjacx function, and my function presumes a usual JSON response:
[{"caseId": 30,"name": "Michael"},{"caseId": 31,"name": "Sara"}]

Batch request with fql using javascript

The following batch request for retrieve friends using the same app is not working:
var search = {batch: [
{
'name' : 'getFriends',
'relative_url': 'method/fql.query?query=SELECT+uid,+first_name,+name,+pic_square,+pic_small+FROM+user+WHERE+is_app_user=1+and+uid+IN+(SELECT+uid2+FROM+friend+WHERE+uid1=' + userId + ')'
},
{
'method': 'get',
'relative_url': '{result=getFriends:$.data[*].uid}/news.reads/article',
}
]};
and the following code executes the batch request:
FB.api('/', 'post', search, function(response) {
console.log(response);
});
but the first search returns null. What's wrong with the query?
According to facebook documentation for batch requests, the *relative_url* is
(...) a relative_url (the portion of the URL after graph.facebook.com)
get from here.
So I changed the first block of code to:
var search = {batch: [
{
'name' : 'getFriends',
'method' : 'GET',
'relative_url': 'method/fql?q=SELECT uid, first_name, name, pic_square, pic_small FROM user WHERE is_app_user=1 and uid IN (SELECT uid2 FROM friend WHERE uid1=me())'
},
{
'method': 'GET',
'relative_url': '{result=getAmigos:$.data[*].uid}/news.reads/article'
}
]};
the relative_url of the first block on the batch works at Open Graph API Tool at facebook, but at the JS the http code is 500 and the message body is:
{
"error": {
"message": "Graph batch API does not allow REST API method fql",
"type": "FacebookApiException",
"code": 3
}
}
but in the api batch requests documentation allows fql queries. The documentation is outdated? Should I open a bug?
P.S: the fql without the batch request is
SELECT uid, first_name, name, pic_square, pic_small
FROM user WHERE is_app_user=1
and uid IN (SELECT uid2 FROM friend WHERE uid1 = me())
Don't use method/fql; Facebook's FQL endpoint is now just fql.
...
"name": "getFriends",
"method": "GET",
"relative_url": "fql?q=SELECT...",
...
it's working now. I just add the access_token parameter at the batch object. like this:
var searchArgs = {
access_token: FB.getAuthResponse().access_token,
batch: []
};
searchArgs.batch.push({
'method': 'GET',
'name': 'amigosapp',
'relative_url': 'method/fql.query?query=SELECT+uid,+first_name,+name,+pic_square,+pic_small+FROM+user+WHERE+is_app_user=1+and+uid+IN+(SELECT+uid2+FROM+friend+WHERE+uid1=me())&limit=20',
'omit_response_on_success': false
});
searchArgs.batch.push({
'method': 'GET',
'relative_url': 'news.reads/article?date_format=U&ids={result=amigosapp:$.[*].uid}'
});
the other trick was use the jsonpath expression in a different way. I couldn't make the second request for each user of the first request. So I changed the way to get it adding the friends ids at the end of the graph api request. I think that my first thought about a request per friend it's not possible using the batch request.
Then I did the call of the batch:
FB.api('/', 'POST', searchArgs,
function(response) {
var friends = response[0].body;
console.log(friends);
var activities = response[1].body;
console.log(activities);
}
);
Now it's just organize the posts retrieved.
[]'s

Categories

Resources