...

/

Creating a Custom REST API

Creating a Custom REST API

Learn to create a custom search endpoint that returns tailored results specifically designed to meet our requirements.

The WordPress REST API can be used to perform basic searches. We cannot perform advanced searches that are aware of relationships between post types. For example, if we search for literature, we get only one result back which is the course post for Literature course. The query wp-json/wp/v2/event?search=literature will return an empty array instead of the two events (Reading Group and Writers Recognition Night) which are related to the literature course. The native search logic of the WordPress REST API searches between obvious fields like title and main body content. It does not search within custom fields and does not know how to interpret the relationships that we set up between different post types.

In order to handle post type relationships efficiently, it becomes necessary to implement a customized REST API that is capable of recognizing and working with these relationships.

Advantages of custom REST API

Building a custom REST API has a number of advantages which are listed below:

  1. The custom REST API will be aware of relationships between post types as the built-in search logic does not cater to our needs.

  2. It can make the search faster as we can control how much data to send. The native REST API sends a lot of data while we only need a title, permalink and a few other properties. Sending less data makes the search faster.

  3. We can return back everything in one URL instead of having to send out a number of asynchronous requests to different URLs. The ...