This article will show you how to use the Fetch API (ES6 +) to make HTTP requests to the REST API, along with some examples for your understanding.
Note: All examples are given in ES6 with arrows.
A common pattern in current Web/mobile applications is to request or display some kind of data (such as users, posts, comments, subscriptions, payments, etc.) from the server and then use CRUD (Create -Create, read -Retrieve, Update -Update, or Delete -Delete) operations.
To further manipulate resources, we often use these JS methods (recommended), such as.map(),.filter(), and.reduce().
What is AJAX for handling asynchronous HTTP requests from JS? Why get the API? Quick introduction to the Fetch API Get the API – CRUD Example ← Good stuff!
1. Process asynchronous HTTP requests from JS
One of the most challenging parts of how JavaScript (JS) works is understanding how to handle asynchronous requests. This requires understanding promises and how callbacks work. In most programming languages, we think of operations as occurring sequentially. The first line must be executed before the next line can proceed. This is obvious because this is how we operate or work, but you can also write code while listening to music. But with JS, we have multiple operations running in the background/foreground, and we can’t freeze a Web application every time we wait for a user event. Describing JavaScript as asynchronous can be misleading. To be more precise, JavaScript is synchronous and single-threaded with various callback mechanisms. But some things have to happen in order, otherwise it can lead to process chaos and unexpected results. For this reason, we can build it using Promises and Callback. Example: User credentials need to be verified before an operation can be performed.
2. What is AJAX
AJAX stands for asynchronous JavaScript and XML and allows Web pages to be asynchronously updated by exchanging data with the Web server while the application is running. In short, it essentially means that you can update parts of a web page without having to reload the entire page (if the URL remains the same). AJAX is a misleading name. AJAX applications may use XML to transfer data, but it is equally common to transfer data as plain text or JSON text. – w3shools.com
AJAX all the way? Many developers get very excited about having all the features in a single page application (SPA), but this can also cause a lot of asynchronous pain! Fortunately, we have libraries like Angular, VueJS, and React, so it’s much easier and easier to write SPA applications. In summary, the balance between reloading the entire page or loading part of the page is very important. For the most part, page reloads work just fine with the increasingly sophisticated capabilities of browsers. In the past, page reloading would have taken a few seconds (depending on server location and browser capabilities). But today’s browsers are fast, so deciding whether to perform AJAX or page reload doesn’t make much of a difference. Personal experience is that in most cases customers don’t care whether it’s a SPA or an extra page reload. Of course, don’t get me wrong, I do love spas, but we need to consider some trade-offs, and if we’re dealing with a limited budget and lack of resources, then a quick solution might be the better approach.
In the end, it really depends on the use case, but I personally feel that SPA requires more development time and dealing with some headaches (the first page load) than simple page reloads.
3. Why Fetch API?
This allows us to make declarative HTTP requests to the server. For each request, it creates a request that Promise must resolve in order to define the content type and access the data.
Now, the nice thing about the Fetch API is that it is fully supported by the JS ecosystem and is part of the MDN Mozilla documentation. Last but not least, it works out of the box on most browsers (IE excepted). In the long run, I suspect it will become the standard way to call Web apis.
Attention! I’m well aware of other HTTP methods, such as using Observables with RXJS, and how it focuses on memory management/leakage in terms of subscribing/unsubscribing, etc. Maybe this will become the new standard way to perform HTTP requests, who knows? Anyway, I’ll just focus on the Fetch API in this article, but may write a future article on Observable and RXJS.
4. A quick introduction to the Fetch API
The fetch() method returns a method that promises to parse the Response from the Request to show the status (success or failure). Don’t be alarmed if you Promise {} receive this message on the console log screen – it basically means promise is working, but waiting to be resolved. So, to solve it, we need a.then() handler (callback) to access the content. So in a nutshell, we first define the path (Fetch), second we define the data (Request) from the server, third we define the content type (Body), and last but not least, we access the data (Response).
Don’t panic if you have trouble grasping the concept. You’ll get a better overview with the examples shown below.
We will be used in the path of the sample https://jsonplaceholder.typicode.com/users / / return JSONCopy the code
5. Obtain an apI-HTTP example
If we want to access the data, we need two.then() handlers (callbacks). But if we want to manipulate resources, we just need a.then() handler. However, we can use the second to ensure that the value has been sent. The first response is just an HTTP response, not real JSON. To get the content of JSON, we can use the JSON () method, in addition to resonance. JSON (), and resonance. Text (); See the Basic Extraction API template in mozilla’s official documentation for details
// The basic module based on fetch fetch.then(response.something) // defines the type and data format to be returned resonance.json().then(data) // The data to be returnedCopy the code
Attention! The above examples are for illustrative purposes only. If you execute it, the code will not work.
Get an API example Display a user Display a user list Create a new user Delete a user update a user
Attention! Resources are not actually created on the server, but return bogus results to mimic the real server.
As mentioned earlier, the process of displaying a single user consists of two.then() handlers (callbacks), the first to define objects and the second to access data. Note that we can understand/predict what the API does simply by reading the query URL string, /users/2. This is one of the great things about REST apis
example
fetch('https://jsonplaceholder.typicode.com/users/2').then(Response => response.json()) // Defines the returned type and data format. Then (data => console.log(data)) // Returned data // Data example: // {//"id": / / 2"name": "Ervin Howell", / /"username": "Antonette", / /"email": "[email protected]", / /"address": {
// "street": "Victor Plains", / /"suite": "Suite 879", / /"city": "Wisokyburgh", / /"zipcode": "90566-7771", / /"geo": {
// "lat": "43.9509", / /"lng": "34.4618"//} //, //"phone": "010-692-6593 x09125", / /"website": "anastasia.net", / /"company": {
// "name": "Deckow-Crist", / /"catchPhrase": "Proactive didactic contingency", / /"bs": "synergize scalable supply-chains"
// }
// }
Copy the code
2. Display a list of users This example is almost identical to the previous example, except that the query string is /users instead of /users/2.
example
fetch('https://jsonplaceholder.typicode.com/users').then(Response => response.json()) // Defines the returned type and data format. Then (data => console.log(data)) // Returned data // Data example: // [// {//"id": / / 1"name": "Leanne Graham", / /"username": "Bret", / /"email": "[email protected]", / /"address": {
// "street": "Kulas Light", / /"suite": "Apt. 556", / /"city": "Gwenborough", / /"zipcode": "92998-3874", / /"geo": {
// "lat": "37.3159", / /"lng": "81.1496"//} //, //"phone": "1-770-736-8031 x56442", / /"website": "hildegard.org", / /"company": {
// "name": "Romaguera-Crona", / /"catchPhrase": "Multi-layered client-server neural-net", / /"bs": "harness real-time e-markets"//} // more... / /]Copy the code
3. Create a new user This looks a little different from the previous example. If you are familiar with the HTTP protocol, it provides many methods, such as POST, GET, DELETE, UPDATE, PATCH, and PUT. These methods are verbs that simply describe the type of action to be performed and are primarily used to manipulate resources/data on the server.
In any case, to create a new user using the Fetch API, we need to use the HTTP predicate POST. But first, we need to define it somewhere. Fortunately, Init we can pass an optional parameter that defines the URL for custom Settings, such as method type, body, credential, title, etc.
example
fetch('https://jsonplaceholder.typicode.com/users',{
method: 'POST',
body: JSON.strignify({
username: 'Joe',
email: '[email protected]',
userId: 1
}),
headers: { 'Content-Type': 'application/json; charset=utf-8'}})Copy the code
To DELETE a user, we first need to locate the user /users/1, and then define the method type DELETE. example
fetch('https://jsonplaceholder.typicode.com/users/1',{
methods: 'DELETE'
})
Copy the code
5. Update the user HTTP predicate PUT to operate on the target resource. If partial changes are to be made, PATCH is required. example
fetch('https://jsonplaceholder.typicode.com/users',{
method: 'PUT',
body: JSON.strignify({
username: 'Joe',
email: '[email protected]',
userId: 1
}),
headers: { 'Content-Type': 'application/json; charset=utf-8'}})Copy the code
conclusion
You now have a basic understanding of how to use JavaScript’s Fetch API to retrieve or manipulate resources from the server and how to handle promises. You can use this article as a guide on how to build API requests for CRUD operations. Personally, I feel that the Fetch API is declarative and that you can easily understand what is going on without any technical coding experience.
Share your thoughts in the comments if you have any questions.