How to send query parameters using Fetch?

Mon Mar 27 2023

5 min read

Sending query parameters is common when making HTTP requests to a server. Query parameters allow you to pass additional information to the server, such as filters, search terms, etc.

The Fetch API provides an easy way to make HTTP requests and supports adding query parameters to the request URL. In this guide, we will explore how to send query parameters when we use fetch API to make an API call.

What are query parameters?

When making a request to a server, you can include query parameters as part of the API endpoint. Query parameters are used to pass additional information to the server about the specific request being made.

These parameters are added to the end of the URL after a question mark (?) and are separated by ampersands (&) if there are multiple parameters.

Let's say you want to make a request to a server to get information about a specific product. You might construct a URL like this:

https://web.com/api/products?id=12345

Similarly, we can also use query parameters for filtering, sorting, or pagination. For example, if you want to get a list of products that are on sale, you might use a URL like this:

https://example.com/api/products?on_sale=true

Using Fetch to send query parameters

Fetch is a JavaScript API used to make API requests. It allows you to send and receive data from servers using various methods such as GET, POST, PUT, DELETE, etc. You can learn more about Fetch API here.

Send a GET Request

To make a GET request with query parameters using Fetch, you'll need to construct the URL with the appropriate parameters and then pass that URL to the fetch method. We will use the Famous Quotes API from the Rapid API Hub for this example.

Loading component...
js
fetch(`https://famous-quotes4.p.rapidapi.com/random?category=all&count=2`, {
method: 'GET',
headers: {
'X-RapidAPI-Key': 'your-rapid-key',
'X-RapidAPI-Host': 'famous-quotes4.p.rapidapi.com'
}
})
.then(response => response.json())
.then(data => console.log(data))
.catch(err => console.error(err));

Encoding Query Parameters

To ensure that the parameters are transmitted correctly and safely, we need to encode them before sending them to the server.

Encoding methods convert special characters and symbols in a URL or query parameter into a format that web servers and browsers can safely transmit and interpret.

There are two main encoding methods: encodeURIComponent and encodeURI. Both methods are built-in JavaScript functions that serve similar purposes but differ in scope and behavior.

The encodeURI function is used to encode an entire URI, including the scheme, hostname, path, and query parameters. It does not encode certain reserved characters, such as ; / ? : @ & = + $ , #, which have special meanings in a URL.

On the other hand, the encodeURIComponent function is used to encode a single query parameter or a string that is part of a query parameter. It encodes all characters with special meanings in a URL, including reserved characters.

Other HTTP methods

Unlike the GET method, HTTP methods such as POST, PUT, and DELETE can also send query parameters. However, sending query parameters with these methods is slightly different. Instead of appending the parameters to the URL, they are sent in the request body.

Here's how to send query parameters with each method.

POST Method

To send query parameters with the POST method, you need to create a request object and set the method to POST. Then, you need to set the Content-Type header to application/x-www-form-urlencoded to indicate that the request body contains URL-encoded data. Finally, you can encode the query parameters using URLSearchParams and set the request body to the encoded data.

js
const data = new URLSearchParams();
data.append('name', 'John');
data.append('email', 'john@example.com');
fetch('/api/users', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: data
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));

PUT Method

The PUT method is used to update an existing resource. To send query parameters with the PUT method, you can use the same approach as with the POST method.

js
const data = new URLSearchParams();
data.append('name', 'John');
data.append('email', 'john@example.com');
fetch('/api/users/1', {
method: 'PUT',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: data
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));

DELETE Method

The DELETE method is used to delete an existing resource. To send query parameters with the DELETE method, you can append them to the URL as with the GET method.

js
const id = 1;
const queryParams = new URLSearchParams({ force: true });
fetch(`/api/users/${id}?${queryParams}`, {
method: 'DELETE'
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));

Wrap Up

Sending query parameters using Fetch is a fundamental skill for developers who want to create dynamic web applications. The Fetch API provides a simple and efficient way to send HTTP requests and receive responses from a server.

If you want to learn more about sending data to the server through fetch, you can read how to send the request body using fetch and set request header using fetch.