How to make API call (CRUD) on React JS - javascript

I'm using Sb-Admin-React. I need to make API call (CRUD) on this framework (Sb-Admin-React), but I have no idea to make it.
May there's anyone can help me to make it out. Thanks

Isomorphic fetch is already included in Sb-Admin-React.
You can make your regular API calls with fetch. It should look something like:
fetch(apiUrl, {
method: method,
headers: headersIfAny,
body: theDataToSend
})
.then(response => /* do something with response */)
.catch(err => /* do something with err */);
You can go through Isomorphic Fetch readme for more info

Related

How do I make an API call server side?

I've created a client-side application that makes an API call. The issue with this, however, is that in order to make the API call, I have to use an API Key. If I make the call client-side, the user will be able to see the API key. How do I avoid this? Well, if the answer is to call the API server-side, how do I do that? There seems to be little information wherever I look regarding server-side programming, and if anyone could lead me in the right way, it would be great.
You have to set it in the header with bearer
let config = {
headers: {
'Authorization': 'Bearer ' + KEY
}
};
Axios.get('http://url', {}, config )
.then( (response) => {
console.log(response)
})
.catch();

JavaScript Fetch API can you access headers as well as JSON in a `.then ` callback?

I need to make a POST request and then depending on the response as well as the headers, I need to update saved state, I know the headers are available via response.header.get('SOME-KEY') and I can access JSON part of the response in a .then callback like so: .then(response => response.json()).then(json =>())
what I want to know is, is there a way to get both in the block which has the parsed JSON response data?
Yes, you can:
.then(response => {
console.log(response.data)
console.log(response.headers)
})
https://github.com/axios/axios#response-schema
Well I don't know how I missed this, the solution was extremely simple, .json() returns a Promise, so we can just call .then on it inside the current context and do what we want with the headers and the response body:
fetch('/url')
.then(response => response.json().then(json => ({...json, token: response.headers.get('TOKEN')})))
.then(json => props.updateUser(json));
In this way we can get the desired object which contains the header values as well as the response data. Sometimes all you need to solve your problem is a bit of sleep.

How to get more API records when the response size is limited

I don't have much experience with React or JavaScript. I am creating a simple application that fetches time series data from an API. The data is used to plot a line chart (React Apex Chart). All good.
The problem is that the API response size is limited to a maximum of 2,000 records, and sometimes we need more data.
The API documentation says:
The response size is limited to a maximum of 2,000 records. If more records have to be returned, the response header contains a Link header with a URI to get the next set of records:
Link: https://apiurl; rel="next"
My Fetch Code:
My code fetches the api data, sorts it and sends it to the child component(Chart).
FetchAPI(){
fetch(https://MYURLHERE?from=FROMDATE&to=TODATE)
.then(response => response.json())
.then(data => this.setState({
kWhData: data.map((kWh) => kWh._kWh),
TimeStampData: data.map((time) => time._time),
loading: false
}))
.catch(error => console.log('Fetching failed', error))
}
Link header: link →<https://MYURLHERE?from=FROMDATE&limit=2000&to=TODATE>; rel="next">
I know the solution may be some kind of pagination but I do not fully understand this concept. I have searched for similar problems with no luck.
Hope someone could provide me with a helping hand, tips or code.
I don't know what API you're using, but it sounds like all you need to do is get the URL to the next set of results from the headers and then make a request to that.
Before you return response.json(), you can access the headers with response.headers.get(). So you can do something like let nextPage = response.headers.get('Link') to get that full Link header as a string. Then you can split it at the semicolon and use the first part as the URL for the next paginated request.
If I've understood the question correctly, I would add a variable to your FetchApi function, so that it can query either your initial API URL, or the URL for a subsequent page:
FetchAPI(requestURL){
// Fetch function here
}
The idea is that this function can then call itself iteratively, with the url of the ‘next’ page of results passed as a parameter for each call, until the response indicates all the data has been retrieved.
So your initial call would be FetchAPI('https://MYURLHERE?from=FROMDATE&to=TODATE').
You can then add a line to call this function again if the rate limit is reached. E.g:
FetchAPI(requestURL){
fetch(requestURL)
.then(response => {
if(response.dataLimit == true){ // Or however this is expressed
// Concat new data with any already retrieved
this.FetchAPI(nextPageUrl) // Get the URL of the next page and call FetchAPI again with this e.g https://MYURLHERE?from=FROMDATE&limit=2000&to=TODATE
} else {
// Otherwise stop and do something else now that you have a complete set of data
}
})
}
Worth saying that this is untested code, but hopefully enough to get the principle across.
Also if the API has a request rate limit e.g. 1 second, you could add a delay before the function calls itself again, though obviously this will impact the overall time to retrieve all of the data.
Thank you all. I got it to work with a mix of both answers.
I do not know if this is a good way to do it or the "right" approach. Maybe you guys could give me some feedback?
The setTimeout was just for testing, but I think I need to have minimum 1000?
The credentials/header is necessary to get the API.
FetchAPI(requestURL) {
fetch(requestURL, {
credentials: 'include',
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
"x-xsrf-token": this.myXRSFToken,
"origin": `${window.location.protocol}//${window.location.host}`
}
})
.then(response => {
let Responseheader = response.headers.get('Link')
response.json()
.then(data => this.setState({
TestData: this.state.TestData.concat(data)
}))
if (Responseheader){
let nextPageUrl = Responseheader.match(/\bhttps?:\/\/\S+Z/gi)
setTimeout(() => {
this.FetchAPI(nextPageUrl)
}, 2000);
} else {
console.log('Done fetching API')
this.setState({
loading: false
})
return
}
})
.catch(error => console.log('Fetching failed', error))
}

Troubleshooting axios requests

I've come across this problem a few times now and I feel like there's someone out there who knows a better way to troubleshoot api calls than i - specifically request headers.
Often when i need to pass my api token via a request header, I am constantly groping at the exact format to pass my key's (it seems there's not a universal format for doing this).
For example, I am currently trying to access the vultr v1 api. The docs give a curl example where API-Key: SOMEKEY needs to be passed, yet, my first attempt rarely works then i'm just groping... Do they want my key in a key/value pair or a single string in an array? Do i use es6 objects (without quotes) or not.
here's what i mean:
// one method
const opts = {
headers: {
API-Key: 'SOMEKEY'
}
}
// another
const opts = {
'headers': {
'API-Key': 'SOMEKEY'
}
}
// another
const opts = {
headers: [
'API-Key: SOMEKEY'
]
}
axios.get(url, opts).then(res => console.log(res.data))
which is the proper way? In the curl example given by vultr it shows:
curl -H 'API-Key: EXAMPLE' https://api.vultr.com/v1/iso/list
I also see in my network inspector that the request headers show i am passing my API key yet i am still getting a 403 (bad key error)
I have double checked the validity of my key and that's not the problem.
My question is this:
How do i find the correct format for the headers? Is there a better troubleshooting method for this kind of problem? Any help would be greatly appreciated. Thanks ya'll
UPDATE:
Turns out they've got access control based on IP's. I hadn't noticed it till just now. They were blocking my request because of this. My question still stands however. Good methods for figuring out correct formats? Is there a correct format?
One way is setting Headers while creating axios object, as follows :
axios = axios.create({headers: {'API-Key': 'EXAMPLE'}});
axios.get(url, opts).then(res => console.log(res.data))
Or
axios.get(url, {headers: {'API-Key': 'EXAMPLE'}}).then(res => console.log(res.data))

poll an http URL and show stats

I'm working on something where I need to poll an http URL and get the numbers available as part of the response and show graphical stats on a web page.
Does anyone know of any opensource software which can do something like this?
Sample URL:
http://dataqueue.com:8080/datamq/message/getcount?q=order.sales&class=com.xyz.entitiy.Order&metadata={}
which Results 15000
then another url would result 10000 etc.
If I understand your question correctly, you can use plain Javascript to achieve something like this. Here's an example that does a server request every five seconds:
function req() {
fetch('http://reqres.in/api/users', {
method: 'post',
body: JSON.stringify({
name: 'morpheus',
job: 'leader'
})})
.then(res => res.json())
.then(json => {
document.getElementById('View').innerHTML = json.id;
});
}
req();
setInterval(() => req(), 5000);
<div id="View"></div>
There are also libraries that make this easier, for example PollJS. You can find more on Github. If you have control over the server, you might want to check out Socket.io.

Categories

Resources