DEV Community

Cover image for REST API Url builder !!
Nitin Reddy
Nitin Reddy

Posted on

3 1

REST API Url builder !!

You must have come across a situation where you are making a REST API call via frontend code and doing something like this -

try {
  const response = await fetch(`/api/users/${userId}/details?name=abc&age=31&height=174&address=xyz`)
  const data = response.json()
  return data;
} catch(err) {
  console.log(`Error: ${err}`)
}
Enter fullscreen mode Exit fullscreen mode

Now in the above example, we tend to pass the whole API endpoint URL string but what if it gets generated automatically for you and you don't need to write the entire URL string.

I have created an npm package nkr_urlbuilder that can help you solve this problem.

Do the following,

import { buildRestUrl } from 'nkr_urlbuilder';

let url = '/api/users/{userId}/details';
let urlParams = {userId: 123};
let queryParams = {
     name: 'abc', 
     age: 31, 
     height: 174, 
     address: 'xyz'
};

try {
  const response = await fetch(buildRestUrl(url, urlParams, 
  queryParams))
  const data = response.json()
  return data;
} catch(err) {
  console.log(`Error: ${err}`)
}
Enter fullscreen mode Exit fullscreen mode

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

SurveyJS custom survey software

JavaScript UI Library for Surveys and Forms

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

View demo

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay