# How to use JavaScript fetch

JavaScript’s `fetch` is an integrated method for sending API requests and helps keep your code tidy. `GET` requests are the default setting, but the API can also be used to send, change and delete data.

## What is JavaScript `fetch` and what are its uses?

JavaScript `fetch` is a way to make [API requests](https://www.ionos.ca/digitalguide/websites/web-development/what-is-an-api/) with Promises. It prevents code from becoming confusing and hard to read and offers numerous other features. `fetch` sends a **request to your server of choice** and executes it in the background. In what follows, we’ll explain how exactly that works and what the `fetch` API has to offer.

## What are the advantages of Promises?

To fully understand JavaScript `fetch`, we’ll first need to look at **Promise objects**. Promises were introduced with JavaScript ES6 and are intended to enable and facilitate the **execution of asynchronous operations**. True to their name, Promise objects entail a kind of promise. If the code works, thereby fulfilling the promise, you’ll get a value. If the promise can’t be fulfilled, you’ll get an error object. As **replacements for or additions to callbacks**, Promises improve the reliability of asynchronous processes and the readability of code.

Promises can have one of the following three states:

- **pending**: The operation has not been either executed or canceled.
- **fulfilled**: The operation was successfully executed.
- **rejected**: The operation failed.

If a promise is fulfilled or rejected, you can react with methods like `then()` and `catch()`. JavaScript `fetch` uses Promises to execute XHR requests to a server.

Tip The perfect use for GitHub! [Deploy Now](https://www.ionos.ca/hosting/deploy-now "Deploy Now from IONOS") from IONOS can be used to deploy changes to code and follow the changes in real time. Choose the plan that best fits your needs.

## How does JavaScript `fetch` work?

The basic syntax of JavaScript `fetch` looks as follows:

```javascript
fetch()
```

The method can take two arguments. The first is a URL that is entered with quotation marks between the parentheses. The second is an object with options that don’t need to be used, which is attached after the instruction itself.

Let’s take a closer look at how this works using this example code:

```javascript
fetch(url)
.then(function() {
})
.catch(function() {
});
```

First we name the URL of the API as a parameter. Then comes the Promise method `then()`, which contains a function. The function will be executed if Promise returns the **variable `resolve`**, which is used for declaring actions as successful. It contains the code necessary for handling the data received from the API.

Below that, we’ve included the `catch()` method. `catch` is called if Promise returns the **variable `reject`**. `reject` is returned when the API can’t be called or another error occurs. In this case, the function contained in `catch()` will be executed. Together these three lines of code account for any possibility and can initiate API requests.

## `GET` requests with JavaScript `fetch`

You can use JavaScript `fetch` to retrieve data from an API. In the following example, we’ll perform a **`GET` request**. This is the **default setting** for JavaScript `fetch`. In the example, we’ll enter a URL, which is answered with a Promise that we then apply the method `then()` to. We’ll then convert the server’s response into a JSON object and use another `then()` method to display the data in the console. The code for all of that looks as follows:

```javascript
fetch("https://exampleurl.com/api")
.then((response) => response.json())
.then((json) => console.log(json));
```

## How to send data with `POST`

While `GET` requests are the default, you can also use JavaScript `fetch` to send data with **`POST` operations**. In the below example, we’ll again start by entering the URL. Then we’ll use the `method` option to specify the request type, which in our case is “POST”. Then come two mandatory options, `body` and `headers`.

`body` contains the data that will be sent to the server. In our case, that consists of the **parameters `title` and `body`**. We also use `JSON.stringify` to convert the data into a string. `headers` is used to specify the data type that will be sent to the server. In our case, it is JSON data and we choose the default encoding UTF-8. Both of these options need to be defined for `POST` requests.

The code for all of the above looks as follows:

```javascript
fetch("https://exampleurl.com/api", {
	method: "POST",
	body: JSON.stringify({
		title: "This is the title",
		body: "This is the content",
	}),
	headers: {
		"Content-type": "application/json; charset=UTF-8",
	},
})
.then((response) => response.json())
.then((json) => console.log(json));
```

## How to update objects with `PUT` or `PATCH`

**`PUT` and `PATCH` requests** are used to completely update objects. They can also be used with JavaScript `fetch`. The approach is similar to the above example. It also requires the `body` option with a string, `JSON.stringify` and the content type `application/json`.

```javascript
fetch("https://exampleurl.com/api", {
	method: "PUT",
	body: JSON.stringify({
		title: "Here is the title",
		body: "Here is the content",
	}),
	headers: {
		"Content-type": "application/json; charset=UTF-8",
	},
})
.then((response) => response.json())
.then((json) => console.log(json));
```

You can also substitute `PUT` with `PATCH`.

## How to remove objects with `DELETE`

JavaScript `fetch` can also be used to delete objects with a **`DELETE` request**. If necessary, you can use `then()` here.

```javascript
fetch("https://exampleurl.com/api", {
    method: "DELETE",
})
.then(() => {
    element.innerHTML = "Deleted";
})
.catch((error) => {
    console.error('Error:', error);
});
```

Tip Looking for more JavaScript tutorials? In our Digital Guide, we have articles on the [popular frameworks and libraries for JavaScript](https://www.ionos.ca/digitalguide/websites/web-development/popular-javascript-frameworks-and-libraries/) and how to [embed JavaScript in HTML](https://www.ionos.ca/digitalguide/websites/web-development/embed-javascript-in-html/).


This is a markdown version of: [https://www.ionos.ca/digitalguide/websites/web-development/javascript-fetch-api/](https://www.ionos.ca/digitalguide/websites/web-development/javascript-fetch-api/) for AI/LLM consumption.