Modern way to consume a json based flask api with javascript - javascript

I'm new to web programming, I been learning the basics of Flask such as http requests, template inheritance, flask forms, saving data on the database etc.
I saw that some people only use flask as backend and its api its json based, and for the frontend they use React. Since I'm learning the basics of JavaScipt I don't want to use libraries like React or Jquery, I want to use just JavaScript. I was searcing and found that many people use AJAX with Jquery, or axios to consume an api. Is there any way to consume my flask api with just JavaScript without using any library or framework?

Is there any way to consume my flask api with just JavaScript without using any library or framework?
Yes, using fetch, which is built in to all modern browsers. A query for data transmitted in JSON format looks like this:
In a non-async function, if you are returning the result of the last call to then:
// Do the request
return fetch("/path/to/the/data", {/*...options if any...*/})
.then(response => {
// Check for HTTP success (`fetch` only rejects on *network* failure)
if (!response.ok) {
// HTTP error
throw new Error(`HTTP error ${response.status}`);
}
// Read the body of the response and parse it from JSON into objects and such
return response.json();
})
.then(data => {
// ...`data` has the data from the call, parsed and ready to go
});
...or if you aren't:
// Do the request
return fetch("/path/to/the/data", {/*...options if any...*/})
.then(response => {
// Check for HTTP success (`fetch` only rejects on *network* failure)
if (!response.ok) {
// HTTP error
throw new Error(`HTTP error ${response.status}`);
}
// Read the body of the response and parse it from JSON into objects and such
return response.json();
})
.then(data => {
// ...`data` has the data from the call, parsed and ready to go
})
.catch(error => {
// ...something went wrong, handle/report `error`...
});
fetch uses promises, so you'll want to read up on those.
In an async function, if you are allowing errors to propagate to the caller:
// Do the request
const response = await fetch("/path/to/the/data", {/*...options if any...*/});
// Check for HTTP success (`fetch` only rejects on *network* failure)
if (!response.ok) {
// HTTP error
throw new Error(`HTTP error ${response.status}`);
}
// Read the body of the response and parse it from JSON into objects and such
const data = await response.json();
// ...`data` has the data from the call, parsed and ready to go
or if you aren't:
try {
// Do the request
const response = await fetch("/path/to/the/data", {/*...options if any...*/});
// Check for HTTP success (`fetch` only rejects on *network* failure)
if (!response.ok) {
// HTTP error
throw new Error(`HTTP error ${response.status}`);
}
// Read the body of the response and parse it from JSON into objects and such
const data = await response.json();
// ...`data` has the data from the call, parsed and ready to go
} catch (error) {
// ...something went wrong, handle/report `error`...
}
More about async functions on MDN.

Related

How to fetch dynamic json with respond.json function using javascript [duplicate]

I am trying to use fetch api to bring back some data, however am unable to map it to the console once I have retrieved it.
fetch('http://jsonplaceholder.typicode.com/users', {
method: 'GET'
}).then(function(response) {
console.log(response)
response.forEach(i => console.log(i.name));
}).catch(function(err) {
console.log(`Error: ${err}` )
});
The error i get is
response.map is not a function
so I tried to parse the response,(ie var data=JSON.parse) which did not work, with the error
SyntaxError: Unexpected token o in JSON at position 1"
Interestingly, when doing the same thing with a XMLHttp request, I was required to parse it, so I would also be interested to know why the difference between these two methods of retrieving the data.
If anyone could point me in the right direction, I would be really grateful.
The Fetch API returns a response stream in the promise. The response stream is not JSON, so trying to call JSON.parse on it will fail. To correctly parse a JSON response, you'll need to use the response.json function. This returns a promise so you can continue the chain.
fetch('http://jsonplaceholder.typicode.com/users', {
method: 'GET'
})
.then(function(response) { return response.json(); })
.then(function(json) {
// use the json
});
Understanding promises is key to using the fetch API.
At the time you're trying to parse your response and loop through it, the response is actually just a promise. In order to utilize the contents of the actual response from the request, you'll have to do some promise chaining.
fetch('http://jsonplaceholder.typicode.com/users').then(function(response) {
// response.json() returns a promise, use the same .then syntax to work with the results
response.json().then(function(users){
// users is now our actual variable parsed from the json, so we can use it
users.forEach(function(user){
console.log(user.name)
});
});
}).catch(err => console.error(err));
It appears that you might be accessing the json incorrectly. You could try calling response.json() instead.
fetch('http://jsonplaceholder.typicode.com/users', {
method: 'GET'
}).then((response) => {
response.json().then((jsonResponse) => {
console.log(jsonResponse)
})
// assuming your json object is wrapped in an array
response.json().then(i => i.forEach(i => console.log(i.name)))
}).catch((err) => {
console.log(`Error: ${err}` )
});
This example is structured to match your example, but ideally, you would return response.json() on that first .then block and proceed on the next block. Here is a similar example that proceeds on the next block.
In your particular case, you can view the Fetch API as a json aware wrapper for "XMLHttpRequest"s. Main differences being that the Fetch API is simpler, functional-like, and has convenience methods. David Walsh does a reasonable comparison in his blog post, which I recommend you take a look at. Plain "XMLHttpRequest"s just pass you whatever string was sent back from the server, it has no idea it could be JSON, and thus leaves it to the user to parse the response whatever way they see fit.

How can I return the response data from Auth0's API on my API?

I'm calling Auth0's API with axios to fetch a list of users. I'm trying to return them using the syntax that I'm using this syntax:
.then(res => {
console.log(res.data) // Prints the deired result
return res.status(200).json(res.data);
})
res.data is printing the desired result. But I'm getting and empty response body on Postman.
I also tried return res.data, only to get a timeout.
What am I missing?
You're calling the status method on the Axios response object when it should be called on the Express response object.
You should name the Auth0 API response something other than res to make sure res inside the callback refers to the Express response object. Or better use destructuring. And you don't have to set the 200 status code since it is set automatically.
.then(({ data }) => res.json(data))

fetch data from json running on node.js

I want to fetch data from JSON object which is on my localhost .
..This might be really stupid question but I am beginner in JS.
and is there any other way to fetch data ??
fetch('http://localhost:3000/show')
.then(result => {
console.log(result);
return result.json();
});
.then(data => {
console.log(data);
});
.catch(error => {
console.log(error);
});
this http://localhost:3000/show contains json objects.
it has retrieved data from mongoose.
Remove the semicolons between each .then call.
Promises use a kind of "monadic" pattern: each method on a promise returns another promise, which has the same API. This means you can chain promise methods indefinitely.
So:
fetch()
.then(/* stuff */)
.then(/* more stuff */)
.catch(/* even more stuff */); // <-- this is the only semicolon
The same is true of many Array methods, so you'll often see code like this:
Object.keys( someObj ) // returns an array
.map(/* iterator function */) // Array.map returns an array
.filter(/* iterator function */) // Array.filter returns an array
.sort(/* comparator function */); // Array.sort returns an array
Again, only one semicolon is needed, because each step of the statement produces an array, and JS lets you anticipate that.
If that doesn't help, you might want to post the error you're getting.
I should add that result.json() will throw if the server at http://localhost:3000/show fails to provide the HTTP header Content-Type: application/json. Even if the response body is entirely valid JSON, the HTTPResponse class refuses to do .json() if the server doesn't state that the content is json.
Also, if this code is running in a browser, and is served from a different host (or port), you will need to do CORS stuff. See https://stackoverflow.com/a/48287868/814463 for possible help.
If your endpoint '/show' returns the json data without any issue, then the below code should console you the json response.
fetch('http://localhost:3000/show')
.then(res => {
console.log(result);
return res.json()
)}
.then(json => console.log(json))
.catch(err => console.log(err));

javascript fetch does not catch 404 error

I have an app with uses a fetch to retrieve information from a 3rd party API. I am calling the API via cors-anywhere-herokuapp.com. When I call the API with valid data, I am able to retrieve the API response and pick up the data I need to pick up. When I call the API with invalid data, the API returns a 404 server error. I am forcing invalid data so I can code to catch this situation. My problem appears to be that the fetch does not catch the 404 error. I have tried coding to inspect the return.status but to no avail. I tried testing return.ok and that didn't work either. This is the code I am executing:
function showProduct(barcode) {
let url = "https://cors-anywhere.herokuapp.com/http://api.barcodelookup.com/v2/products?barcode=" + barcode + "&key=mj1pm32ylcctxj1byaia85n9dk2d4i";
url = "https://cors-anywhere.herokuapp.com/http://api.barcodelookup.com/v2/products?barcode=5000159459211&key=mj1pm32ylcctxj1byaia85n9dk2d4i";
const options = { method: 'GET' };
fetch( url, options)
.then(function(response) {
return response.json();
})
.then(function(myJson) {
if (myJson == undefined)
{
console.log("fetch failed")
}
else
{
//inspect the data that the WebAPI returned
document.getElementById("showScanner").style.visibility = "hidden";
document.getElementById("scanner-container").style.visibility = "hidden";
document.getElementById("showProductDiv").style.visibility = "visible";
document.getElementById("productManufacturer").innerHTML = myJson.products[0].manufacturer;
document.getElementById("productName").innerHTML = myJson.products[0].product_name;
document.getElementById("productDescription").innerHTML = myJson.products[0].description;
Quagga.stop();
}
});
}
and this is what I see in the debugger when I execute the code
When I look at the debugger network tab, and click on Headers, I see this:
So, my question is, how do I capture the status code?
According to the documentation on fetch's response, you should be able to testthe status code of the response that fetch's Promise resolves to using response.status.
Note that although it's unintuitive, the Promise fetch returns only rejects when there's a connection error. If the connection succeeds and there's a response, this promise will resolve with the response, even if the status code is non-200.

Access SonarQube API with FetchAPI doesn't return any result

I am trying to access SonarQube API through Fetch but it doesn't seem to be responding with any results. It just resolves with an opaque token.
Let me share what I have done so far:
fetch("http://localhost:9000/api/issues/search?pageSize=500&componentKeys=bactch_analysis_key",{
mode:'no-cors'
}) // Call the fetch function passing the url of the API as a parameter
.then(
res => res.json()
)
.then(data => {
console.log(data);
})
.catch(err => {
console.log(err);
});
I am setting the mode as no-cors as it was throwing ACAO errors.
The same URL works perfect when openend from chrome or inspected through Postman.
This is what I get when the promise resolves:
Below is the error that I get from the catch clause:
SyntaxError: Unexpected end of input
at fetch.then.res (index.html:51)

Categories