Understanding Fetch() API in Javascript
Published: 2023-10-20 18:18:06

This article covers all you need to know about the **FETCH()** API and how to **get started** I'm very sure you will be glad as you're about to read this helpful **material** **let's go !!!!!**

**What's API**
API simply stands for application programming interface, this abbreviation explains it all because it's straightforward, it enables a smooth interaction between two computers i.e. it enables a user to get data into its computer from another computer with a a method called fetch.

**Types of API**
* **RESTful APIs:** Representational State Transfer APIs use HTTP 
     methods (GET, 
  POST, PUT, DELETE) and are designed around resources. They are 
  widely used for web services and are typically accessed over the internet. 
A simple REST API endpoint and its response typically follow a standard structure. Here's an example of what a simple REST API endpoint and its response might look like:
Endpoint: `/api/users`
HTTP Method: GET
Request: To retrieve a list of users.
Response:
```js
[
  {
    "id": 1,
    "username": "user123",
    "email": "user123@example.com"
  },
  {
    "id": 2,
    "username": "johndoe",
    "email": "johndoe@example.com"
  },
  {
    "id": 3,
    "username": "alice",
    "email": "alice@example.com"
  }
]
```
In this example:

The endpoint `/api/users` represents a resource for retrieving a list of users. The HTTP method used is GET, which is used to request data from the server. The response has an HTTP status code of 200 OK, indicating that the request was successful.
The Content-Type header specifies that the response is in JSON format. The response body is a JSON array containing a list of user objects, each with an `id`, `username`, and `email field`.
This is a simplified example, and real-world APIs may have more complex endpoints and responses, but the basic structure of an endpoint and its response in a RESTful API typically includes the HTTP method, endpoint URL, status code, headers, and a data payload in a standard format like JSON or XML.

* **GraphQL APIs:** A query language for APIs, GraphQL allows clients to request only the specific data they need, reducing over-fetching and under-fetching of data you can learn more about the types of GraphQL here https://dev.to/callebdev/understanding-graphql-and-its-design-principles-fd6


## Now what's FETCH, and how to use it
in the context of API (application interface) "FETCH" typically refers to making an HTTP request to retrieve data from a server or send it, it's a common term used when discussing web APIs.

### Here's an overview of the syntax and key components of the Fetch API: 
**Basic Fetch Syntax:**
To make a basic GET request using the Fetch API, you can use the following syntax:
```js
fetch(url)
  .then(response => response.json())
  .then(data => {
    // Handle JSON data here
  })
  .catch(error => {
    // Handle errors here
  });
```
* *`fetch(url):`* This initiates a GET request to the specified URL and returns a Promise that resolves to the Response object representing the response to the request

* *The first `.then()`* is responsible for handling the response itself, which includes checking the HTTP status code, headers, and other metadata. It's typically used to convert the Response object into the format that you need, such as parsing it as JSON or extracting specific information. Inside this .then() block, you receive the Response object as an argument.

* *The second `.then()`* is used to work with the data obtained from the response. It executes after the first .then() and receives the result of the previous .then() as its argument. This is where you can perform further processing on the parsed data, use it in your application, or update the user interface.
 
* *`.catch(error => { ... }):`* This callback is executed if there is an error during the request, such as a network issue or a request that failed for some other reason

now that we understand what is fetch, to use the fetch function in javascript to make HTTP requests to an API you can follow this step            
I built a Rick and Morty app from which I get all the data I need via javascript fetch API and I think this a perfect resource to
practice it(fetch API) link to the final project https://opeyemi-2018.github.io/cartoon/



               
you can just follow this step
**1. Create an HTML file copy and paste the below code inside the body element**


```html
<div class="main-con">
  <div class="logo">
    <img src="images/rick_and_morty.png" alt="" />
  </div>

  <div class="api-container">
         <div class="api-container">
        <!-- <div id="Api-output">
                  <div class="img">
                     <img src="" >
                  </div>
                    <div class="info-div">
                      <h2>ope</h2>
                      <h3>ondo</h3>
                      <h3>ondo</h3>
                      <h4>20</h4>
                </div>
            </div> -->
      </div>
  </div>
</div>
<script src="main.js"></script>
```

**2. Create a CSS file copy and past below code inside**
```css
body {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  background: #03001c;
  font-family: sans-serif;
}

.main-con {
  padding: 4% 4%;
}

.logo {
  color: #fff;
  padding: 3% 2%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.logo img {
  width: 15%;
}

.api-container {
  display: grid;
  grid-template-columns:
    1fr 1fr
    1fr;
  column-gap: 10px;
  row-gap: 10px;
}

#Api-output {
  border: 1px solid #fff;
  background-color: #27374d;
  padding: 3px 1%;
  border-radius: 10px;
}
img {
  width: 25%;
  border-radius: 50%;
}

.img {
  display: flex;
  align-items: center;
  justify-content: center;
}

.info-div {
  background: rgb(4, 87, 87);
  border-radius: 5px;
  border: 1px solid gray;
  color: white;
  padding-top: 10px;
}

.info-div h2,
h3,
h4 {
  margin-left: 10px;
  font-size: 16px;
}

@media screen and (max-width: 850px) {
  .api-container {
    display: grid;
    grid-template-columns:
      1fr
      1fr;
  }
}

@media screen and (max-width: 600px) {
  .api-container {
    display: grid;
    grid-template-columns: 1fr;
  }
}

```

**3. Create a javascript file e.g. (`script.js`) where you will write your code. In the script.js file Use the "fetch function" You can store the URL in a variable** 

```js
let URL = "https://rickandmortyapi.com/api/character"
```
     
or you write it directly in the fetch method. to write it directly in the fetch method you can simply follow these steps, you create a function since we will be calling the function to make the program run

```js  
function getApiData() {
  fetch("https://rickandmortyapi.com/api/character")
    .then((res) => res.json())
    .then((data) => {
      data.results.forEach((post) => {
        apiContainer.innerHTML += `
                 <div id="Api-output">
                   <div class="img">
                     <img src="${post.image}">
                   </div>
                   <div class="info-div">
                      <h2> Name: ${post.name}</h2>
                      <h3> Location: ${post.location.name} 
                      </h3>
                   <h4>No of movies: ${post.episode.length} 
                   </h4>
                 </div>
               </div>
              `;
      });
    });
}
getApiData();
```
          
so let's go through the steps and explain what each 
method does
          
1. the fetch is used to make an HTTP request GET request to 
   the specified URL, it returns a promise that resolves to the 
   response from the server

2. since fetch uses promise we use `.then()` to handle 
   the response, the promise will return another promise
   you will notice the first `.then()` has a `JSON()` method
   just to specify we're expecting JSON data
    
3. we use the second `.then()` to get the useful data we needed 
   because the first `.then()` return some irrelevant stuff
   
4. we use the catch error function for debugging
   to handle any error that might come up while sending our 
   request
5. we loop through the data using forEach method to get each of 
   the data that contains the image of each character, name, the 
   number of the episodes they appear 
6. We dynamically populate the data into the HTML code that we 
   have already styled.

**Conclusion
  This article is intended to provide you with fundamental 
  knowledge on how to fetch an API.**