Explain Codes LogoExplain Codes Logo

Setting query string using Fetch GET request

javascript
prompt-engineering
async-await
url-search-params
Nikita BarsukovbyNikita Barsukov·Nov 20, 2024
TLDR

To swiftly integrate query parameters to your Fetch GET request, you can make use of JavaScript's URLSearchParams:

const params = new URLSearchParams({ search: 'term', limit: '5' }).toString(); fetch(`https://api.example.com/items?${params}`) .then(res => res.json()) .then(data => console.log(data));

This little code chunk connects your base URL with encoded query parameters and kicks off the request.

The power of encoding and appending parameters

When crafting a URL with parameters for a GET request, it's vital to ensure correct encoding. Use URLSearchParams to get it right:

const baseURL = 'https://api.example.com/search'; const searchParams = new URLSearchParams({ 'main-category': 'books', 'sub-category': 'fiction', 'sort-by': 'popularity' }); const encodedURL = `${baseURL}?${searchParams.toString()}`; fetch(encodedURL) .then(response => response.json()) .then(results => console.log(results)) .catch(error => console.error('Error:', error));

By taking care of the encoding, you're preventing bugs and making sure you're speaking the same language as your server!

Enhancing readability with async/await

For your asynchronous functions, consider using async / await for a neat and clean look:

async function fetchData() { const params = new URLSearchParams({ page: '1', count: '10' }).toString(); const response = await fetch(`https://api.example.com/items?${params}`); // The await keyword is like putting a bookmark in a book. I'll be back... 👋 return response.json(); // And I'm back! 😎 } fetchData().then(data => console.log(data));

The use of async / await simplifies asynchronous GET requests, resulting in manageable code that even your grandma can read (assuming she knows JavaScript 😜).

Extracting the most out of URLSearchParams

URLSearchParams isn't just about initializing. It offers a plethora of methods to add, delete, modify or loop through query parameters:

let searchParams = new URLSearchParams({ author: 'Hemingway' }); // Getting ready to search for some Hemingway searchParams.append('published', '1952'); // The Old Man and the Sea? searchParams.set('author', 'Orwell'); // Change of plan. Let's get inspired by 1984 searchParams.delete('published'); // Does it really matter when it was published? // This is how to go on a literary tour: for (let p of searchParams) { console.log(p); }

Remember, with URLSearchParams, you're in control!

Broaden your compatibility with Polyfills

Need to support Internet Explorer or some older browsers? Polyfills got your back for using fetch and URLSearchParams:

// Kick off your JavaScript file with the inclusion of polyfills import 'whatwg-fetch'; // Fetch polyfill import 'url-search-params-polyfill'; // URLSearchParams polyfill

Hey, dinosaurs like Internet Explorer also deserve some love ❤️!

Considerations for Node.js

Starting from version 18, Node.js includes native support for both fetch and URLSearchParams. If you're on an earlier version or using TypeScript, consider some additional imports:

// Older Node.js versions need 'node-fetch' const fetch = require('node-fetch'); const { URLSearchParams } = require('url'); // TypeScript/Node.js <10 users const params = new URLSearchParams({ foo: 'bar' }); // Simple, yet iconic 😄

Why not explore third-party fetch utilities?

axios or query-string libraries are more than capable of simplifying encoding and decoding, especially in complex application logic:

import axios from 'axios'; import { stringify } from 'query-string'; const params = stringify({ filter: 'active', tags: ['print', 'virtual'] }); axios.get(`https://api.example.com/posts?${params}`) .then(response => console.log(response.data));

When in doubt, remember there's always a library for that! 📚

Crafting maintainable code with functions

Covering fetch along with the formulation of the query string into functions comes handy when trying to improve readability, reuse, and overall manageability:

function createQueryString(params) { return Object.keys(params) .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`) // Encoding in progress... .join('&'); } async function fetchWithSearchParams(url, queryParams) { const queryString = createQueryString(queryParams); const response = await fetch(`${url}?${queryString}`); return response.json(); } // Here's how to use it fetchWithSearchParams('https://api.example.com/search', { query: 'JavaScript' }) .then(data => console.log(data));

Remember, smart coders create functions, brilliant ones reuse them! 😉

Flexibly combining search parameters

When handling complex data, you can construct your query string using arrays. This approach is particularly useful if you want to represent multiple values for the same key:

const params = new URLSearchParams(); params.append('topic', 'search-queries'); params.append('topic', 'fetch'); // Double the trouble here 😃 console.log(params.toString()); // "topic=search-queries&topic=fetch"

When dealing with array parameters, you can conveniently adopt functions such as stringify from the query-string library:

import { stringify } from 'query-string'; const paramsString = stringify({ tags: ['nodejs', 'vuejs', 'express'], approved: true }, { arrayFormat: 'comma' }); fetch(`/api/posts?${paramsString}`);

Arrays, who knew they could be so flexible? 😉