fetching api code example
Example 1: javascript fetch api
fetch('http://example.com/movies.json')
.then((response) => {
return response.json();
})
.then((data) => {
console.log(data);
});
Example 2: fetch
// This will fetch api.example.com/comments with a header and a body
fetch(`https://api.example.com/comments`, {
method: 'POST', //This could be any http method
headers: {
'Authorization': 'Basic SGVsbG8gdGhlcmUgOikgSGF2ZSBhIGdvb2QgZGF5IQ==',
'Content-Type': 'application/json',
},
body: JSON.stringify({
UID: 58,
Comment: "Fetch is really easy!",
}),
})
.then((response) => response.json())
.then((newComment) => {
// Do something magical with your newly posted comment :)
});
Example 3: fetch api javascript
fetch('http://example.com/movies.json')
.then((response) => {
return response.json();
})
.then((myJson) => {
console.log(myJson);
});
Example 4: fetch api in javascript
// GET Request.
fetch('https://jsonplaceholder.typicode.com/users')
// Handle success
.then(response => response.json()) // convert to json
.then(json => console.log(json)) //print data to console
.catch(err => console.log('Request Failed', err)); // Catch errors