DEV Community

Sanjampreet Singh
Sanjampreet Singh

Posted on

7 1

Simplifying API Calls with URLSearchParams and Fetch

Have you ever had to deal with complicated query parameters while using GET API calls?

Introducing URLSearchParams, a JavaScript interface that makes it simple to manage query parameters.

Let's explore how it might raise the bar for your Fetch method use.

// Create a new URLSearchParams object
const params = new URLSearchParams({
    'search': 'keyword',
    'filter': 'category',
    'sort': 'date'
});

// Combine with your API endpoint
const apiUrl = `https://api.example.com/data?${params}`;

// Fetch the data
fetch(apiUrl)
  .then(response => response.json())
  .then(data => {
    // Handle your data here
  })
  .catch(error => {
    // Handle errors
  });

Enter fullscreen mode Exit fullscreen mode

URLSearchParams: We may create, modify, and manage query parameters within URLs using this convenient interface. It is ideal for writing exact API calls without manually adding '&' and '=' symbols.
Use URLSearchParams to generate a clean, well-organized parameter string rather than manually concatenating strings.

Benefits of using URLSearchParams

  • Clean code: No more manual parameter concatenation!
  • Readable: Easily understand query parameters at a glance.
  • Dynamic: Add, remove, or update parameters effortlessly.

If you like what you read, consider connecting with me on LinkedIn

Top comments (5)

Collapse
 
iamhectorsosa profile image
Hector Sosa

Nice post! I've written a simple package to handle URLSearchParams with full type-safety called @search-params/react -> github.com/iamhectorsosa/search-pa....

Check it out and let me know what you think. If you find it useful, I'd appreciate a star on GitHub

Collapse
 
sanjampreetsingh profile image
Sanjampreet Singh

Thanks Hector!!

Collapse
 
webjose profile image
José Pablo Ramírez Vargas • Edited

I suppose the keys and values are URL encoded? This is nice. I had no idea this existed. Had I known, I would have used it in wj-config.

Collapse
 
sanjampreetsingh profile image
Sanjampreet Singh

I would encourage you to read more about it on MDN. Even, I recently discovered this and thought of sharing with the community in a plain language.

Collapse
 
anasouzas profile image
Ana Souza

Nice post! It helped me a lot.