Setting query string using Fetch GET request

JavascriptJqueryHttpFetch Api

Javascript Problem Overview


I'm trying to use the new Fetch API:

I am making a GET request like this:

var request = new Request({
  url: 'http://myapi.com/orders',
  method: 'GET'
});
fetch(request);

However, I'm unsure how to add a query string to the GET request. Ideally, I want to be able to make a GET request to a URL like:

'http://myapi.com/orders?order_id=1'

In jQuery I could do this by passing {order_id: 1} as the data parameter of $.ajax(). Is there an equivalent way to do that with the new Fetch API?

Javascript Solutions


Solution 1 - Javascript

A concise, modern approach:

fetch('https://example.com?' + new URLSearchParams({
    foo: 'value',
    bar: 2,
}))

How it works: When a string (e.g. the URL) is being concatenated with an instance of URLSearchParams, its toString() method will automatically be called to convert the instance into a string representation, which happens to be a properly encoded query string. If the automatic invoking of toString() is too magical for your liking, you may prefer to explicitly call it like so: fetch('https://...' + new URLSearchParams(...).toString())

A complete example of a fetch request with query parameters:

// Real example you can copy-paste and play with.
// jsonplaceholder.typicode.com provides a dummy rest-api
// for this sort of purpose.
async function doAsyncTask() {
  const url = (
    'https://jsonplaceholder.typicode.com/comments?' +
    new URLSearchParams({ postId: 1 }).toString()
  );

  const result = await fetch(url)
    .then(response => response.json());

  console.log('Fetched from: ' + url);
  console.log(result);
}

doAsyncTask();


If you are using/supporting...

  • IE: Internet Explorer does not provide native support for URLSearchParams or fetch, but there are polyfills available.

  • Node: As of Node 18 there is native support for the fetch API (in version 17.5 it was behind the --experimental-fetch flag). In older versions, you can add the fetch API through a package like node-fetch. URLSearchParams comes with Node, and can be found as a global object since version 10. In older version you can find it at require('url').URLSearchParams.

  • Node + TypeScript: If you're using Node and TypeScript together you'll find that, due to some technical limitations, TypeScript does not offer type definitions for the global URLSearchParams. The simplest workaround is to just import it from the url module. See here for more info.

Solution 2 - Javascript

Update March 2017:

URL.searchParams support has officially landed in Chrome 51, but other browsers still require a polyfill.


The official way to work with query parameters is just to add them onto the URL. From the spec, this is an example:

var url = new URL("https://geo.example.org/api"),
    params = {lat:35.696233, long:139.570431}
Object.keys(params).forEach(key => url.searchParams.append(key, params[key]))
fetch(url).then(/* … */)

However, I'm not sure Chrome supports the searchParams property of a URL (at the time of writing) so you might want to either use a third party library or roll-your-own solution.

Update April 2018:

With the use of URLSearchParams constructor you could assign a 2D array or a object and just assign that to the url.search instead of looping over all keys and append them

var url = new URL('https://sl.se')

var params = {lat:35.696233, long:139.570431} // or:
var params = [['lat', '35.696233'], ['long', '139.570431']]

url.search = new URLSearchParams(params).toString();

fetch(url)

Sidenote: URLSearchParams is also available in NodeJS

const { URL, URLSearchParams } = require('url');

Solution 3 - Javascript

let params = {
  "param1": "value1",
  "param2": "value2"
};

let query = Object.keys(params)
             .map(k => encodeURIComponent(k) + '=' + encodeURIComponent(params[k]))
             .join('&');

let url = 'https://example.com/search?' + query;

fetch(url)
  .then(data => data.text())
  .then((text) => {
    console.log('request succeeded with JSON response', text)
  }).catch(function (error) {
    console.log('request failed', error)
  });

Solution 4 - Javascript

As already answered, this is per spec not possible with the fetch-API, yet. But I have to note:

If you are on node, there's the querystring package. It can stringify/parse objects/querystrings:

var querystring = require('querystring')
var data = { key: 'value' }
querystring.stringify(data) // => 'key=value'

...then just append it to the url to request.


However, the problem with the above is, that you always have to prepend a question mark (?). So, another way is to use the parse method from nodes url package and do it as follows:

var url = require('url')
var data = { key: 'value' }
url.format({ query: data }) // => '?key=value'

See query at https://nodejs.org/api/url.html#url_url_format_urlobj

This is possible, as it does internally just this:

search = obj.search || (
    obj.query && ('?' + (
        typeof(obj.query) === 'object' ?
        querystring.stringify(obj.query) :
        String(obj.query)
    ))
) || ''

Solution 5 - Javascript

You can use stringify from query-string.

import { stringify } from 'query-string';

fetch(`https://example.org?${stringify(params)}`)

Solution 6 - Javascript

encodeQueryString — encode an object as querystring parameters

/**
 * Encode an object as url query string parameters
 * - includes the leading "?" prefix
 * - example input — {key: "value", alpha: "beta"}
 * - example output — output "?key=value&alpha=beta"
 * - returns empty string when given an empty object
 */
function encodeQueryString(params) {
	const keys = Object.keys(params)
	return keys.length
		? "?" + keys
			.map(key => encodeURIComponent(key)
				+ "=" + encodeURIComponent(params[key]))
			.join("&")
		: ""
}

encodeQueryString({key: "value", alpha: "beta"})
 //> "?key=value&alpha=beta"

Solution 7 - Javascript

I know this is stating the absolute obvious, but I feel it's worth adding this as an answer as it's the simplest of all:

const orderId = 1;
fetch('http://myapi.com/orders?order_id=' + orderId);

Solution 8 - Javascript

Maybe this is better:

const withQuery = require('with-query');

fetch(withQuery('https://api.github.com/search/repositories', {
  q: 'query',
  sort: 'stars',
  order: 'asc',
}))
.then(res => res.json())
.then((json) => {
  console.info(json);
})
.catch((err) => {
  console.error(err);
});

Solution 9 - Javascript

Solution without external packages

to perform a GET request using the fetch api I worked on this solution that doesn't require the installation of packages.

this is an example of a call to the google's map api

// encode to scape spaces
const esc = encodeURIComponent;
const url = 'https://maps.googleapis.com/maps/api/geocode/json?';
const params = { 
    key: "asdkfñlaskdGE",
    address: "evergreen avenue",
    city: "New York"
};
// this line takes the params object and builds the query string
const query = Object.keys(params).map(k => `${esc(k)}=${esc(params[k])}`).join('&')
const res = await fetch(url+query);
const googleResponse = await res.json()

feel free to copy this code and paste it on the console to see how it works!!

the generated url is something like:

https://maps.googleapis.com/maps/api/geocode/json?key=asdkf%C3%B1laskdGE&address=evergreen%20avenue&city=New%20York

this is what I was looking before I decided to write this, enjoy :D

Solution 10 - Javascript

Template literals are also a valid option here, and provide a few benefits.

You can include raw strings, numbers, boolean values, etc:

    let request = new Request(`https://example.com/?name=${'Patrick'}&number=${1}`);

You can include variables:

    let request = new Request(`https://example.com/?name=${nameParam}`);

You can include logic and functions:

    let request = new Request(`https://example.com/?name=${nameParam !== undefined ? nameParam : getDefaultName() }`);

As far as structuring the data of a larger query string, I like using an array concatenated to a string. I find it easier to understand than some of the other methods:

let queryString = [
  `param1=${getParam(1)}`,
  `param2=${getParam(2)}`,
  `param3=${getParam(3)}`,
].join('&');

let request = new Request(`https://example.com/?${queryString}`, {
  method: 'GET'
});

Solution 11 - Javascript

Was just working with Nativescript's fetchModule and figured out my own solution using string manipulation. Append the query string bit by bit to the url. Here is an example where query is passed as a json object (query = {order_id: 1}):

function performGetHttpRequest(fetchLink='http://myapi.com/orders', query=null) {
    if(query) {
        fetchLink += '?';
        let count = 0;
        const queryLength = Object.keys(query).length;
        for(let key in query) {
            fetchLink += key+'='+query[key];
            fetchLink += (count < queryLength) ? '&' : '';
            count++;
        }
    }
    // link becomes: 'http://myapi.com/orders?order_id=1'
    // Then, use fetch as in MDN and simply pass this fetchLink as the url.
}

I tested this over a multiple number of query parameters and it worked like a charm :) Hope this helps someone.

Solution 12 - Javascript

var paramsdate=01+'%s'+12+'%s'+2012+'%s';

request.get("https://www.exampleurl.com?fromDate="+paramsDate;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmylesccView Question on Stackoverflow
Solution 1 - JavascriptScotty JamisonView Answer on Stackoverflow
Solution 2 - JavascriptCodingIntrigueView Answer on Stackoverflow
Solution 3 - JavascriptSudharshanView Answer on Stackoverflow
Solution 4 - JavascriptyckartView Answer on Stackoverflow
Solution 5 - JavascriptHirurg103View Answer on Stackoverflow
Solution 6 - JavascriptChaseMoskalView Answer on Stackoverflow
Solution 7 - JavascriptEvertView Answer on Stackoverflow
Solution 8 - JavascriptBin HOUView Answer on Stackoverflow
Solution 9 - JavascriptCarlosView Answer on Stackoverflow
Solution 10 - JavascriptPat KearnsView Answer on Stackoverflow
Solution 11 - JavascriptAmjad AbujamousView Answer on Stackoverflow
Solution 12 - JavascriptKirubakaran RView Answer on Stackoverflow