In this guide, I’ll show you how to use the Fetch API (ES6+) to perform HTTP requests to an REST API’s
REST API – jsonplaceholder
Rest API – Grepper
Usefull tool for HTTP Testing is Postman
Here’s what we’ll address
- Dealing with JS’s asynchronous HTTP requests
- What is AJAX?
- Why Fetch API?
- A quick intro to Fetch API
- Fetch API – CRUD examples ← the good stuff!
1. Dealing with JS
JavaScript is always synchronous and single-threaded. If you’re executing a JavaScript block of code on a page then no other JavaScript on that page will currently be executed.
JavaScript is only asynchronous in the sense that it can make, for example, Ajax calls. The Ajax call will stop executing and other code will be able to execute until the call returns (successfully or otherwise), at which point the callback will run synchronously. No other code will be running at this point. It won’t interrupt any other code that’s currently running.
JavaScript timers operate with this same kind of callback.
Describing JavaScript as asynchronous is perhaps misleading. It’s more accurate to say that JavaScript is synchronous and single-threaded with various callback mechanisms.
jQuery has an option on Ajax calls to make them synchronously (with the async: false option). Beginners might be tempted to use this incorrectly because it allows a more traditional programming model that one might be more used to. The reason it’s problematic is that this option will block all JavaScript on the page until it finishes, including all event handlers and timers.
2.What is AJAX
AJAX stands for Asynchronous JavaScript and XML.
AJAX is a misleading name. AJAX applications might use XML to transport data, but it is equally common to transport data as plain text or JSON text. More at :
— w3shools.com
3.Why Fetch API
This allows us to perform declarative HTTP requests to a server. For each request, it creates a Promise which must be resolved in order to define the content type and access the data.
4.Intro to Fetch API
The fetch() method returns a Promise that resolves the Response from the Request to show the status (successful or not).
In our examples we'll use
https://jsonplaceholder.typicode.com/todos/1 // returns JSON
5. Fetch API Example
If we want to access the data, we need two .then() handlers (callback).
// Template
fecth(url)
.then(response.something) // Define response type (JSON, Headers, Status codes)
.then(data) // get the response type
// Practical example
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(data => console.log(JSON.stringify(data)))
More can be found at: HERE
Leave A Comment?