JavaScript, along with HTML and CSS, are key programming languages. Nearly every site on the web uses JavaScript, so understanding its native Application Programming Interface (API) is important if you want to become a well-rounded developer.
In this post, we’ll introduce you to the Fetch API and what it can do. Then we’ll discuss how it’s different from the WordPress REST API, and explain when you might want to use it in your WordPress development.
Let’s jump right in!
An Introduction to the Fetch API
Like all APIs, the Fetch API is used for sending and receiving data between applications. As its name suggests, it’s primarily used for ‘fetching’ resources using HTTP requests and then modifying them. In that way, it works much like an XMLHttpRequest.
However, the Fetch API offers an improvement over that method, by using cleaner code to achieve the same end result. It does that by returning data in the form of ‘promises’, which are a simplified, more readable solution that’s replaced callbacks for enabling developers to execute JavaScript functions in a specific order.
Essentially, a promise states that a certain action will eventually occur, and provides information on what should happen next when it does. A promise always either ‘resolved’ (resulting in a response) or ‘rejected’ (resulting in an error).
If the promise is resolved, a .then handler executes the specified action. In the event that the promise is rejected, an error message may be displayed instead using a .catch function. Since JavaScript is asynchronous, all of this happens in the background without preventing the rest of the page from rendering.
So when we put this all together, we get an API that retrieves resources as promises. It then returns response objects if those promises are resolved, or errors if they’re rejected. You can also add .then or .catch handlers to immediately follow the response or error with another action.
Here’s a simple example: Let’s say you use the Fetch API to retrieve a list of posts. The post data is returned as a promise, which is resolved and results in a response object. Next you use a .then handler to return that response as JSON, which you can display on your website. As you can see, this API offers a lot of potential, especially for specific applications.
How the Fetch API Differs from the WordPress REST API
In short, apart from the fact that they’re both APIs, the Fetch API and the WordPress REST API are different in just about every way. A few key distinctions include:
- The Fetch API returns data as promises, while the WordPress API returns data as JSON.
- Likewise, you must use a .then handler to convert data returned by the Fetch API into JSON.
- You can return data in forms other than JSON via the Fetch API.
- In order to use promises with the WordPress REST API, you’ll need to write them yourself after calling the API.
If you want to use the Fetch API with WordPress, you simply have to call the fetch function in your JavaScript code. Follow that function with a .then handler to access the content. You can then display it on your website or in your web application.
2 Times You May Want to Use the Fetch API Over the REST API
You can probably accomplish just about anything you might want to do with the Fetch API by using the WordPress REST API instead. However, the Fetch API does provide a couple of handy features that aren’t as accessible via the native WordPress API. Let’s look at two examples.
1. Returning a Response That Is Not JSON
As we already mentioned, when you use the WordPress REST API, it returns JSON data by default. However, there may be times when you need your response in a different form. To make that work with the WordPress API, you’d have convert the JSON into your desired format somewhere along the line.
The Fetch API, on the other hand, is capable of returning data in several different formats. While JSON is probably the most popular form for Fetch API responses, you can also use it to return responses in a wide variety of other formats, including XML, HTML, plain text, and blobs.
To do so, you simply change the response method specified within the .then handler that you use to access the content you’ve retrieved. For example, here’s a very simplified Fetch API call, followed by a .then handler that returns the response as JSON:
fetch('https://jsonplaceholder.typicode.com/todos') .then(response => response.json()) .then(data => console.log(JSON.stringify(data)))
So, if you would like to return the data as XML instead, you could use response.text instead of response.json. This is much easier than carrying out a conversion after retrieving data with the WordPress REST API.
2. Using Promises to Execute Functions in a Particular Order
Additionally, if you want to use promises with the responses to your WordPress REST API calls, it may be more efficient to simply use the Fetch API instead. With the WordPress API, you would need to write your own promise following the request and response, whereas the Fetch API will return the promise for you.
If you’re using an API to request data, and then want to use JavaScript functions to do something else with that data, the Fetch API may be the way to go. For instance, consider this example:
var eventsURL = "https://api.seatgeek.com/2/events?q=amway-center&client_id=MTI3NjI2NjF8MTUzNDYxMjQ1MS4zNA"; fetch(eventsURL) .then((response) => response.json()) .then(function (evnt) { return evnt.events.map(function(event){ var singleEvent = document.createElement('li'); var eventDate = document.createElement('span'); var newDate = moment(event.datetime_local).format('LLL'); singleEvent.innerHTML = event.title; eventDate.innerHTML = newDate; append(eventlist, singleEvent); append(singleEvent, eventDate); }) }) .catch(function (error) { console.log('Error during fetch: ' + error.message); });
Here, we can run an event function by adding a .then handler to the promise returned by the Fetch API, in order to display events from the site SeatGeek. Promises can make using JavaScript much easier, and keep your code cleaner and more readable. In turn, this could make your development both more efficient and effective.
Conclusion
When it comes to web development, you won’t get very far without JavaScript. Having a handle on its native API will help you easy retrieve resources that you can modify for use on your website or web application.
In this post, we discussed two examples of when you might want to use the JavaScript Fetch API instead of the WordPress REST API:
- Returning a response that is not JSON. With the Fetch API, you can return data in a variety of formats, while the WordPress REST API returns only JSON.
- Using promises to execute functions in a particular order. Since the Fetch API returns data as promises, you won’t have to write your own.
Do you have any other questions about the Fetch API? Leave them in the comments section below!
Article Thumbnail Image Sudowoodo / shutterstock.com
am happy to see that I am not by any means the only one who is overwhelmed by this article.
I was continually thinking did he make a new API to bring information out of WordPress, no he didn’t!
Thanks for sharing this tutorial. I was looking for this type of information from the last 3 to 4 days.
Is there any way to replace the default WordPress REST API with your Fetch API ?
I would like to move to fetch api instead of default wordpress api because fetch api will be much more effective than wordpress api.
Could you please help me on this ?
I am glad to see that I am not the only one who is blown away by this article.
I was constantly thinking did he make an new API to fetch data out of WordPress, no he did NOT!
So how does he get his data out of WordPress, I’m still wondering how.
Garbage article. Any API can be accessed with fetch or ajax. Comparing WP’s API to JS’S Fetch method is literally comparing apples to oranges.
Like the others have said, leave the tech articles to the people who actually know what they’re talking about vs someone who is going to spew pure garbage. LEARN 2 CODE PLZ
This above is a prime example why SEO copywriters should not try to write about technical topics they have no clue about. I am sure Elegant Themes have competent developers who could point mr. Hughes to the right direction and help fix all the factual mistakes in this article.
I was wondering if it was just me thinking this didn’t make any sense… :-/