We usually use libraries over raw XHR and Fetch because libraries can make it much easier for us to code.
I’m not going to share how it makes it easier here because there are a lot of details. You’re going to find out what these details are in the next chapter.
The library we’re going to use
The most popular libraries are Axios and ky.
But we’re not going to use either of those in this course.
We’re going to use a library called zlFetch. We use it because it’s the library I’m most familiar with. (I made the library and I use it in all my projects).
Don’t worry if you’re not using a popular library in this course. These libraries are all similar in principle so you can switch to a different library anytime.
By the way, as you go through the lessons, you may begin to like zl-fetch over the other libraries more and more. That’s because I put a ton of work into designing an easy-to-use API 🙂.
Installing zl-fetch
If you’re using a browser, you can download zlFetch with an import statement.
To use an import statement, you need to make sure your script has type set to module
<script type="module"> import zlFetch from 'https://cdn.jsdelivr.net/npm/zl-fetch/src/index.js'</script>If you’re using Node, or if you’re using Frameworks like Astro, React, Vue, and Svelte, you can install zlFetch via npm.
npm install zl-fetch --saveimport zlFetch from 'zl-fetch'Feel free to read the docs for more information on zlFetch. It will be a handy guide when you’re tackling more advanced stuff later.
Fetching with zlFetch
Sending a basic request with zlFetch is the same as sending a basic request with fetch — you write the url and options you wish to use:
zlFetch('https://link-to-resource', options)When receiving responses, zlFetch makes it easy for you by automatically converting the data into a JavaScript object.
To get the data, you just have to look at the body property.
zlFetch('https://link-to-resource', options).then(response => { const data = response.body})Fetch vs zlFetch
Here’s a basic comparison between fetch and zlFetch.
// Fetchfetch('https://link-to-resource', options) .then(response => response.json()) .then(data => { // Do something with Data })
// zlFetchzlFetch('https://link-to-resource', options).then(response => { const data = response.body // Do something with Data})This is a basic example of how libraries can simplify the fetching process.
Most libraries do many other things on top of this basic example I’m showing you right now. We’ll explore what are some of these things are later in the Rest API chapter.
For now, let’s take a look at the core JavaScript concepts you must understand before you look at Rest APIs.
Welcome! Unfortunately, you don’t have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson