How to use fetch API to get an Array back? - javascript

I have an API which will return an array to me.
I tried to use fetch API to get the array back.
I know that if I use fetch to acquire some data, the real body in the response is ReadableStream.
I usually to deal with it by response.json() in then function if data is json.
What I don't know is how to deal with array data?

If your API is not returning a JSON array [1,2,3] then you can use the .text function to get the raw value:
fetch('/api/text').then(function(response) {
return response.text()
}).then(function (text) {
// parse the text here how you want, for csv:
// return text.split(',')
})
Otherwise you can simply just use the .json method to get the array value.
The ArrayBuffer that you mention is to read a binary buffer, it can be useful for fetching songs or etc... If your API is returning this, I would check out the link to see what you can do. You will most likely be required to decode the buffer and how that is done is completely dependent on how your API is encoding it and I cannot answer that without more detail regarding your API response.

Related

How to use GraphQL response as a variable in Javascript

I am new to GraphQL and I am have the query working as expected but I am having trouble working with the response.
Query
query {
all_assets(where: {title: "suppliestile-blt9607aa6a28539d2e.zip"}) {
items {
url
}
}
}
Calling Response
var jsondata = JSON.stringify(response.data);
console.log(jsondata);
This is giving me the following response
{"data":{"all_assets":{"items":[{"url":"https://assets.contentstack.io/v3/assets/blt15ad871ba49b8a41/blta52af33b959c061f/6352b5fb3bd922566d8d3f2d/suppliestile-blt9607aa6a28539d2e.zip"}]}}}
Essentially I would like to use the url value as a variable moving forward but I am having trouble extracting it from all of the nested objects and arrays does anyone have any advice to get me pointed in the right direction?
The answer won't differ because it's a Graphql request. It's just a response that you get through the request via response.data.
If you need to access specific object/property within the response , you need to use the index of the object, you can do
const url = response.data.all_assets.items[0].url;

Axios adds constant name as outline to JSON, how do I only send the body?

I'm trying to send a POST request to a REST API that I have created. The POST request is sent from a Reactjs application.
The JSON I want to send looks like this:
{
"name":"something"
}
My plan was to send it like this:
const json = {
"name" : "something"
}
Axios.post("http://localhost:8080/BackendWiki/api/brands/", {json})
.then(res => {
console.log(res);
console.log(res.data);
})
But when I do that the JSON that is sent looks like this:
{
"json"{
"name":"something"
}
}
an then the API can't process the request. Is there a way to only send the body of the constant? I know that I can send the request like this:
Axios.post("http://localhost:8080/BackendWiki/api/brands/", {"name":"something"})
.then(res => {
console.log(res);
console.log(res.data);
})
and that works, but I would like to send a bit more complicated JSON than just one hardcoded line. So, is there a good way to solve this?
{} is a new object.
{json} is a new object with a property named json that has the value of the variable of the same name.
If you don't want to wrap your data in a new object… don't.
Axios.post("http://localhost:8080/BackendWiki/api/brands/", json)
NB: The value of the json variable is an object. It doesn't get turned into JSON until somewhere inside the Axios library. You should probably give it a more descriptive name (such as brand).
Remove the {} wrapping your object reference. The data argument expects an object and json already is one.
note that is a poor choice of variable names since it is not actually json data which is a string data format
Axios.post("http://localhost:8080/BackendWiki/api/brands/", json)
By wrapping json {} in brackets, (in the Axios.post call), you are making a nested json object. Removing those should fix the problem.

fetching the data dynamically from RestEnd points

I need to get the data from the REST endpoint and display it in some sort of filterable table, and update it if anything changes in the server.
(I dont want to get the data from static JSON file but everytime i make a GET call to rest end point i will get the data which is in json format)
are there any tutorials which can help me with this?
To make a fetch call to an API endpoint, you would use JavaScripts built in fetch method. See below, I've built a fetch and even put in a dummy endpoint that returns actual JSON so you can see that it's working. Just replace the URL right after fetch with the the API endpoint you want to get JSON from...
fetch('https://jsonplaceholder.typicode.com/users')
.then((response) => {
return response.json()
})
.then((data) => {
console.log(data)
})
.catch((err) => {
console.log(err)
})
The first .then makes sure the data is turned back into JSON and then passes the data down to the second .then. Inside that second .then is where you would handle the response by using (in this case) 'data' as the variable name. You can set those parameters to whatever you want to call them though. Finally, the .catch simply console logs the error message if the fetch is unsuccessful.
Here is a repl so you can see it working. Just hit run and you'll see the response: https://repl.it/repls/UnfoldedVibrantProcessor
You'll need to continuously call the API endpoint to check for the data, updating the local dataset with each response. If the API is self-developed,restful and used solely for this example, then the data will be cached so it won't have a massive impact on performance/resources (if the data isn't changing rapidly).
Just shove the code you're using to call the endpoint e.g. Ajax calls within a setInterval() loop and it should work fine, updating the UI (table & contents) as you're re-performing the process over and over.
setInterval(function(){
some AJAX call getting data ...
... use the AJAX response (data) to re-draw/update the table contents
}, 3000);
The process for getting what you want:
Implement continuous API caller (setInterval); initiated on document load.
Learn and Implement external API request e.g. AJAX
Parse data, create HTML using data to create a table structure or use external table library.
Use created HTML to dynamically modify the DOM using document.getElementById("#table you made in your html").innerHTML = ^#3

Using fetch() Webapi

I am trying to see how browser's native webapi fetch() api works. So far I have this: Sample-Code and it works fine. But what I don't understand why is it streaming string which I have to convert to a JSON? I am not sure why would anybody even need to stream a JSON as string through a REST API? I am pretty sure I am missing something here but I am not sure how I should tell fetch() to get the response as JSON and not as a ReadableByteStream which I have to convert to a string and parse it for a JSON.
My Question is this,
Why is a string being streamed here?
How do I tell fetch() to fetch my response as text or json so that I can do response.json() or response.text() as mentioned in the docs? (FYI I tried adding a header object and creating a Header instance and passing it to fetch() neither changed my response.
All you need to do is call
fetch("https://api.github.com/users/ajainarayanan").then(res => res.json());
Here is some modified code the has the same result
fetch("https://api.github.com/users/ajainarayanan")
.then(res => res.json())
.then(res => console.log('Profile: ', JSON.stringify(res, null, 2)));
Apparently I have to do response.json() in one then handler and have the actual value in subsequent then handlers. Update-code. What I didn't realize was response.json() returned another Promise which I should handle like a promise. So console.log(response.json()) will naturally just console log a JSON object instead of my actual json. Thank your #aray12 for you answer. I didn't realize the answer until I realize .json() returned a promise.
PS: Adding this as an answer as I couldn't add this in comments.

AngularJS $http.put PUT Method not sending Data

I'm switching from jquery $.ajax, which was working fine, to using AngularJS $http.put to access a restful API.
I can make an API call, but the PUT data isn't getting sent - so my API sees a PUT request with an empty data object, which should contain a JSON string -> data.values = 'a json structure'
$http.put(
$rootScope.api_url,
{
values: jsonifiedValues
},
{
headers: {
apihash: sha256hash
}
}).success(function(data,status,headers,config){
// handle success
}).error(function(data,status,headers,config) {
// handle failure
});
I've not used AngularJS's $http before, but when I dump out the data in my PHP api it's just empty. this is how I'm pulling it from the request in the PHP:
parse_str(file_get_contents('php://input'), $put_vars);
$arr_req_data = $put_vars['values'];
In my API if the apihash sent from the request doesn't match the sha256 hash built on the PUT values, it fails.
This is working in JQuery, just failing now I've switched to $http. I'm not sure why the PUT data seems to be empty.
The return value from file_get_contents('php://input') will be a JSON string (provided everything got sent), so parse_str is not the right function to handle that data.
Instead use json_decode.
Also there is no need to send jsonified values, it will just make things more complicated as you'll have to use json_decode twice.

Categories