Your first GraphQL API

Search is another complementary technical when working with a large dataset. It takes an existing list, and removes items based on criteria that match/don't match.

In this tutorial, we are going to implement a search for our data table.

Table Of Content

  1. Understanding GraphQL searching mechanism
  2. Implementing searching
  3. The end
1. Understanding GraphQL searching mechanism

Search happens when we pass in a search parameter and it scans multiple fields behind the scene to get the data we want. We can use the same idea to implement filters, except that filters work in one single field.

Search can go together with pagination or alone. In our case, we are going to combine search and pagination.

2. Implementing searching

An imaginary searching request would look like this:

Note that we are using a generic "search" parameter for the query argument:

Since in a search request, we are trying to narrow down the result, there is no need to paginate the result.

Let's add "search" parameter to the ArticlesConnection field.

Modify build method of ArticlesConnection class:

Next step is to make resolve method capable of searching the results based on our request. Normally this method will delegate to the other service class from business layer, and the service class will search the results with some sort of database calls. However, because our fake repository class simply returns a static array, we are going to sort with PHP array method array_filter.

Modify resolve method of ArticlesConnection class:

That is all the change we need for ArcilesConnection class and the final file should be as shown below:

Lastly, we need to create a simple request to search the result using "search" parameter:

Create a new file tutorial-search.php:

Access the page from the browser of your choice via the URL http://your-local-php-server/tutorial-search.php.

You should expect a JSON output as shown below if you have followed this tutorial correctly:

Try to change the "search" parameter's value and see how GraphQL searching reflects.

4. The End

Next tutorial, we are going to show you how to implement nested queries in GraphQL and see how GraphQL loads data dynamically on the fly.
If you like our post, please follow us on Twitter and help spread the word. We need your support to continue.
If you have questions or find our mistakes in above tutorial, do leave a comment below to let us know.