> For the complete documentation index, see [llms.txt](https://wplake.gitbook.io/advanced-views/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://wplake.gitbook.io/advanced-views/post-selections/component-options/rest-api-actions.md).

# Selection Rest Api actions

In Advanced Views, every [*Post Selection*](/advanced-views/getting-started/first-post-selection.md) is a smart entity, natively supporting the [WordPress Rest Api](https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/).&#x20;

It enables you to create components that can send data and/or update themselves in the background without refreshing the page.

#### Server side:

To use this feature, we override the  `get_rest_api_response()` method inside the [Selection Controller](/advanced-views/post-selections/code-fields/selection-controller.md) instance. The return value should be an array, which will be passed as `JSON` to the client.

Within the callback, you can use any WordPress functions. Furthermore, you can [employ PHP-DI](/advanced-views/post-selections/code-fields/selection-controller.md) to get direct access to your theme classes.

#### Client side:

On the client side, as usual, we send requests to the `/wp-json` endpoint.

## 1. Rest Api vs. Ajax

Not sure about the difference between WordPress Ajax and REST API?&#x20;

**In most cases, we recommend using the REST API**. It is much faster compared to the traditional `admin-ajax.php` requests, as it skips loading unnecessary WordPress parts - while still making all necessary WordPress functions available - as it is called during the WordPress `init` action.

If you need to work with authorized users, Ajax may be the simpler option, as it respects the auth cookie within requests; therefore, it doesn't require Request Authentication parts.

## 2. Selection Rest Api example

#### JavaScript code

Incorporate the following function into your [*Post Selection's* JavaScript code](/advanced-views/post-selections/code-fields/javascript-code.md):

<pre class="language-javascript"><code class="lang-javascript"><strong>async function makeRequest(postId, value) {
</strong>// we use '/wp-json/advanced_views/v1/post-selection/' endpoint for Layout, 
// and put a specific Selection ID at the end (copy it from the shortcode)

    await fetch('/wp-json/advanced_views/v1/post-selection/{6630e2da1953e}', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
        // todo your arguments here
           'postId': postId,
            'value': 'value,
        }),
    }).then(response => response.json())
        .then((response) => {
            // todo process response, the variable already contains the parsed object 
            console.log('Request complete', response);
        })
        .catch(error => () => {
            console.error('Request error:', error)
        });
}
</code></pre>

#### *Selection* Controller code

Incorporate the following function into your [Selection Controller](/advanced-views/post-selections/code-fields/selection-controller.md):&#x20;

```php
<?php

declare( strict_types=1 );

use Org\Wplake\Advanced_Views\Bridge\Controllers\Selection\Selection_Controller_Base;

return new class extends Selection_Controller_Base {
// ..other methods go here
	/**
	 * @return array<string,mixed>
	 */
	public function get_rest_api_response( WP_REST_Request $request ): array {
		$request_arguments = $request->get_json_params();
		// todo process the request, based on the query arguments available inside the array

		// todo you can use the container if you need to access your theme classes
		// $this->get_container();

		return [
			'my_message'  => 'everything is fine',
			'my_variable' => 'my value',
		];
	}
};

```

## **3. Request Authentication**

The REST API is available to both authorized users and guests; however:

{% hint style="warning" %}
For security reasons, **by default the REST API ignores the WordPress auth cookie and treats any request as if it comes from an unauthorized user.**&#x20;
{% endhint %}

It means `wp_get_current_user()->exists()` method inside the request will return `false`.

If you need to keep the user authorized inside the request, you must create a `wp_rest` nonce and pass it in the `X-WP-Nonce` header, as [it described](https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/) in the official WordPress Developer Documentation. In this case, WordPress will respect the user's auth cookie.

Below, we provide the auth example adopted for use inside the Advanced Views:

#### **3.1) Selection Controller: create and pass nonce to the template**

```php
// ...
/**
 * @return array<string,mixed>
 */
public function get_variables(): array {
  return [
    "my_block_nonce" => wp_create_nonce( 'wp_rest' ),
  ];
}
// ...
```

#### **3.2) Selection template: define nonce as a JavaScript variable**

```html
<!-- ... -->
<script>
window.my_block_nonce = "{{ my_block_nonce }}";
</script>
<!-- ... -->
```

#### **3.3) Selection JavaScript: use nonce in the request headers**

<pre class="language-javascript"><code class="lang-javascript"><strong>// ...
</strong>await fetch('/wp-json/advanced_views/v1/{view|card}/{6630e2da1953e}', {
 method: 'POST',
 headers: {
  'Content-Type': 'application/json',
  'X-WP-Nonce': window.my_block_nonce,
},
// ...
</code></pre>
