# Understanding the Basic Syntax of fetch() in JavaScript

When working with APIs in JavaScript, `fetch()` is one of the most commonly used Web APIs to make HTTP requests.

Let’s break it down step by step 👇

### 1️⃣ Basic Syntax of `fetch()`

```javascript
fetch(url, options);
```

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| url | string | ✅ Yes | API / endpoint URL |
| options | object | ❌ No | Request configuration |

### 2️⃣ Simplest Syntax (GET Request)

```javascript
fetch("https://api.example.com/data");
```

**Default Behavior**

When you call `fetch()` like this, it automatically uses:

* **Method → GET**
    
* **No request body**
    
* **No custom headers**
    

This is perfect for simply retrieving data.

### 3️⃣ Syntax with `.then()`

Since `fetch()` returns a Promise, we handle the response using `.then()`.

```javascript
fetch(url, options)
  .then((response) => response.json())
  .then((data) => console.log(data))
  .catch((error) => console.error(error));
```

### 4️⃣ Syntax with `async/await`

A cleaner and more readable way 👇

```javascript
const response = await fetch(url, options);
const data = await response.json();
```

Used inside an `async` function:

```javascript
async function getData() {
  const response = await fetch(url);
  const data = await response.json();
  console.log(data);
}
```

### 5️⃣ Full Options Syntax

When you want full control over the request:

```javascript
fetch(url, {
  method: "POST",          // HTTP method
  headers: {               // Request headers
    "Content-Type": "application/json",
  },
  body: JSON.stringify({   // Request body
    key: "value",
  }),
  mode: "cors",            // CORS mode
  credentials: "include",  // Cookies handling
  cache: "no-cache",       // Cache control
  redirect: "follow",      // Redirect handling
  signal: controller.signal // Abort request
});
```

## Q: When Do We Use the `options` Object in `fetch()`?

---

Whenever we want to customize the request beyond the default **GET** call.

### 1️⃣ When Sending Data to Server (POST / PUT / PATCH)

GET requests don’t send a body, but POST/PUT do — so options are required.

```javascript
fetch("/api/users", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    name: "Shubham",
  }),
});
```

## 2️⃣ When Sending Custom Headers

Example: Authorization token

```javascript
fetch("/secure", {
  headers: {
    Authorization: "Bearer token",
  },
});
```

---

## Q: Why Do We Send Body as `JSON.stringify()`?

Because HTTP request bodies support only:

* Text
    
* Binary data
    

They **do NOT understand JavaScript objects directly**.

So we convert:

👉 JavaScript Object → JSON String

```javascript
JSON.stringify();
```

### 🧠 Think of It Like Language Translation

* JavaScript Object → Browser language
    
* JSON String → Internet / Server language
    

### 1️⃣ What Happens If You DON’T Stringify?

```javascript
fetch("/api", {
  method: "POST",
  body: { name: "Shubham" }, // ❌ Wrong
});
```

Browser converts object into a string like:

```javascript
[object Object]
```

Server receives garbage data ❌

### 2️⃣ Correct Way

```javascript
fetch("/api", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    name: "Shubham",
  }),
});
```

Now request body becomes:

```javascript
{"name":"Shubham"}
```

### Server understands it ✅  
  
3️⃣ Why JSON Specifically?

Because JSON is:

* Text-based
    
* Language independent
    
* Lightweight
    
* Easy to parse
    

Every backend understands JSON:

* Node.js → `JSON.parse()`
    
* Python → `json.loads()`  
    

# ✅ Final Thoughts

`fetch()` is simple at the surface but powerful when you use the `options` object.
