How to Send GET and POST Requests with JavaScript Fetch API
Tags: wordpress
Published: 2021-03-02 10:09:46

It's a common task for JavaScript developers to <strong>send GET and POST requests</strong> to retrieve or submit data. There are libraries like Axios that help you do that with beautiful syntax. However, you can achieve the same result with a very similar syntax with Fetch API, which is supported in all modern browsers.

<!--more-->

Using the Fetch API, you don't have to install an external library and thus, reduce the built file size. And you can still have a beautiful syntax with little code. Let's do that!

<img class="aligncenter" src="https://i.imgur.com/ngaJZgT.jpeg" alt="How to Send GET, POST Requests with JavaScript Fetch API" width="6000" height="4000" />

<h2>Sending Requests with Fetch API</h2>

To send a GET request with Fetch API, use the following code:

<pre>fetch( 'https://domain.com/path/?param1=value1&amp;param2=value2' )

    .then( response =&gt; response.json() )

    .then( response =&gt; {

        // Do something with response.

    } );

</pre>

To send a POST request, use the following code:

<pre>const params = {

    param1: value1,

    param2: value2; 

};

const options = {

    method: 'POST',

    body: JSON.stringify( params )  

};

fetch( 'https://domain.com/path/', options )

    .then( response =&gt; response.json() )

    .then( response =&gt; {

        // Do something with response.

    } );

</pre>

You can see the main difference between GET and POST requests is how the parameters are passed to the <code>fetch</code> call. In most cases, developers expect to pass an object of parameters and send requests in a beautiful syntax like this:

<pre>const params = {

    param1: value1,

    param2: value2; 

};

const response = get( url, params );

// or

const response = post( url, params );

</pre>

To do that, we need some code to transform the original code with <code>fetch</code> to the new syntax.

<h2>Creating <code>get</code> and <code>post</code> Functions</h2>

Because the codes that send requests are similar between GET and POST, we'll create a common function <code>request</code> to make a request first. And then use it to create <code>get</code> and <code>post</code> functions like this:

<pre>const request = ( url, params, method ) =&gt; {

    // All logic is here.

};

const get = ( url, params ) =&gt; request( url, params, 'GET' );

const post = ( url, params ) =&gt; request( url, params, 'POST' );

</pre>

Now it's time to build the <code>request</code> function.

Note that for each function, we have a different way to construct parameters: they're in the URL for GET, and in the body for POST. Thanks to <code>URLSearchParams</code> we can transform an object to a query string for the GET request.

Here is the first version:

<pre>const request = ( url, params = {}, method = 'GET' ) =&gt; {

    let options = {

        method

    };

    if ( 'GET' === method ) {

        url += '?' + ( new URLSearchParams( params ) ).toString();

    } else {

        options.body = JSON.stringify( params );

    }

    return fetch( url, options ).then( response =&gt; response.json() );

};

const get = ( url, params ) =&gt; request( url, params, 'GET' );

const post = ( url, params ) =&gt; request( url, params, 'POST' );

</pre>

The above code returns a promise, and you can use it in your app like this:

<pre>get( 'https://domain.com/path', { param1: value1, param2: value2 } )

.then( response =&gt; {

    // Do something with response.

} );

</pre>

You can see it in action on <a href="https://codesandbox.io/s/requests-yctc5?file=/src/index.js">CodeSandbox</a>.

<img class="aligncenter" src="https://i.imgur.com/fgyilP6.jpg" alt="Send GET, POST Requests easily using JavaScript Fetch API" width="6000" height="4000" />

<h2>Caching Requests</h2>

One problem developers usually need is <a href="https://metabox.io/review-cache-plugin-speed-up-website/#what-is-cache">caching</a> requests, to avoid sending the same request multiple times.

To implement caching, we can create an object to store the data and use it to return the data earlier:

<pre>let cache = {};

const request = ( url, params = {}, method = 'GET' ) =&gt; {

    // Quick return from cache.

    let cacheKey = JSON.stringify( { url, params, method } );

    if ( cache[ cacheKey ] ) {

        return cache[ cacheKey ];

    }

    let options = {

        method

    };

    if ( 'GET' === method ) {

        url += '?' + ( new URLSearchParams( params ) ).toString();

    } else {

        options.body = JSON.stringify( params );

    }

    const result = fetch( url, options ).then( response =&gt; response.json() );

    cache[ cacheKey ] = result;

    return result;

};

</pre>

<h2>WordPress REST API</h2>

As a WordPress developer, I usually work with the WordPress REST API. While the code above works fine in a general JavaScript app, it needs some changes to work in WordPress.

To send a request to the WordPress API, you need to authenticate the request. Also, the URL for REST requests must contain the WordPress base URL. Here is the updated code:

<pre>let cache = {};

const request = ( url, params = {}, method = 'GET' ) =&gt; {

    let cacheKey = JSON.stringify( { url, params, method } );

    if ( cache[ cacheKey ] ) {

        return cache[ cacheKey ];

    }

    let options = {

        method,

        headers: { 'X-WP-Nonce': MyApp.nonce }, // Add nonce for WP REST API

    };

    // Setup the rest base URL for requests.

    url = `${ MyApp.restBase }/url`;

    if ( 'GET' === method ) {

        url += '?' + ( new URLSearchParams( params ) ).toString();

    } else {

        options.body = JSON.stringify( params );

    }

    const result = fetch( url, options ).then( response =&gt; response.json() );

    cache[ cacheKey ] = result;

    return result;

};

</pre>

To send <code>restBase</code> and <code>nonce</code> to JavaScript, we need to use the <code>wp_localize_script</code> function as follows in your plugin or theme PHP file:

<pre>wp_enqueue_script( 'my-app', plugin_dir_url( __FILE__ ) . 'js/app.js', [], '1.0', true );

wp_localize_script( 'my-app', 'MyApp', [

    'restBase' =&gt; untrailingslashit( rest_url() ),

    'nonce'    =&gt; wp_create_nonce( 'wp_rest' ),

] );

</pre>

After that, you can make requests like this:

<pre>get( 'my-namespace/my-endpoint', { param1: value1, param2: value2 } )

.then( response =&gt; {

    // Do something with response.

} );

</pre>

<h2>Conclusion</h2>

This post shows you how to make basic GET, POST requests in JavaScript with the Fetch API. It also shows you how to make requests for the WordPress REST API. With little code, we can have a beautiful syntax like in other libraries. You can use this method in your general JavaScript app or in a WordPress plugin.

I also wrote an article about <a href="https://metabox.io/modernizing-javascript-code-in-wordpress/">modernizing JS code</a> (improving and modernizing a large JavaScript codebase). So if you're interested, you can read it to have a better code.

Happy coding!