Skip to main content

Override Query Parameters with tweak

ยท 3 min read

It's really hard to express the power of tweak just through our documentation. Some use cases fall through the cracks. We got some recent feedback on users searching for a way to modify URL query parameters and not being able to find it in tweak. This short "how to" article explains how you can manipulate the URL and its query parameters with tweak in just 3 simple steps.

1. Create the rule with an appropriate URL expressionโ€‹

Through the use of regular expressions (toggling the .* button) or through a catch-all partial URL rule you are able to target your desired URL without specificying all the nitty gritty details of the URL such as the query parameters or entity identifiers. Here's an example where we'll grab all the GET requests for "Game of Thrones" characters without specifying their identifier in the URL.

tweak rule with broad URL expression

2. Use a modify rule with a request hookโ€‹

Toggle the rule to Modify. Modify rules will allow you to manipulate the URL using JavaScript as we'll see next. Click the Request hook editor tab and write the code to manipulate the URL.

writing a script to modify the query parameters

Expand to get the full JS code used in the example.
// Grab string after ?.
const urlParams = new URLSearchParams(url.split('?')[1]);

// If "continent" param is preset override its value.
if (urlParams.has('continent')) {
urlParams.set('continent', 'weOverrideContinentWithThisValue');
}

const finalUrl = `${url.split('?')[0]}?${urlParams.toString()}`;

return {
method,
// Don't forget to return the modified URL here.
url: finalUrl,
body,
headers,
};

3. Trigger the request again with the rule activeโ€‹

As show in the above screenshot triggering the request again after activating your modify rule actives overrides the query parameter with your desired value. That's all โœ….

What else can you do?โ€‹

There's really no limit, here's some ideas:

  • Modify the URL entirely, e.g. forward the request to some other server or endpoint.
  • Generate random query parameters using JavaScript to fullfill a myriad of testing use cases.
  • Use console.tables to print a structured view of the URL query parameters.
  • Write your own generic script that can modify any URL query parameters given an object with key value pairs (query param, query param value) ๐Ÿš€

And so much more. It's really up to you how you leverage the power of request hooks. If you're finding this pattern useful there's a very high change that you'll find response hooks just as useful.



If you liked this article, consider sharing (tweeting) it to your followers.



Did you like this article?