How to Filter Using GraphQL: A Simple Tutorial

APIs are the most common way to communicate with the back-end and front-end of applications today. These programming interfaces allow developers to provide a simple solution for making data available to whoever or whatever needs it. There are two popular API types: REST and GraphQL. We’ll focus on the second, more specifically, how to do GraphQL filtering.

In technology, new methods and concepts are constantly emerging. Each has its advantages and disadvantages. Developed by Facebook, GraphQL offers a much more efficient and powerful alternative to REST. With no data hassle, GraphQL lets you perform declarative searches, where a client specifies exactly what data it needs from the API. So now, instead of having multiple endpoints, GraphQL only exposes one. In addition, it responds efficiently and accurately to the data requested. Let’s start going into the details.

How does GraphQL filtering work?

GraphQL is a query language for APIs. You can use a lot of programming languages ​​to implement it. There are two main parts: the client and the server. You can choose from some of the available solutions. But we’ll focus on Apollo Server and Apollo Client when we take a closer look at our GraphQL filtering examples.

Reasons to use GraphQL

Let’s examine them one by one.

  • Network performance: GraphQL is ideal when you want to increase network performance by sending less data or only necessary and relevant information to clients.
  • The project choice “Include request X additional endpoints:” The hardest choice when developing API projects is whether to include the request or create an additional endpoint. But with GraphQL, this problem is solved because it relies on schema and resolver functions. This way the client has control over what data should be returned.
  • Management of different types of customers: Imagine you have an API and all your clients (iOS apps, Android apps, web apps, etc.) are completely different. Each needs a totally different structure or a different amount of data returned from the server. With the REST approach, you can create a separate API. In contrast, with GraphQL you don’t need a separate API because you can return everything from a single endpoint.
GraphQL API Filtering

A concrete example of GraphQL filtering

One of the main issues developers face when using REST APIs is that you may get more or less information than your front-end application actually needs. We commonly use the terms overexploitation and under-extraction to describe these situations.

In contrast, when you write and use a GraphQL query, the application can get exactly the required fields. This is one of the main advantages. After all, you don’t want to spend more resources than necessary.

Let’s dive into a simple example to show how filtering actually works on the server side. Consider the following GraphQL schema:

Type Movie {

I did!

title: Channel

year: International

director: director

}

type Query {

movie(id: ID!): Movie

}

We have now defined the Movie type and a type named Query to allow us to retrieve data on a Movie by providing an identifier. Thus, the movie field expects an identifier of type ID and returns the data concerning the movie. In this case, we allow the application to filter out a specific item.

How could we recover the data? It’s quite simple, take a look at the code below:

request getMovieById {

movie (id: “9”) {

Title

year

}

}

It is important to understand that every field in GraphQL has a Resolver function. For example, from the getMovieById request, a resolver function could be generated so that if the client called that request, its API would return a response, the Movies JSON in this case. This behavior is performed in a resolver function. The resolver for the Movie field would look like this:

const resolvers = {

To question: {

movie(parent, arguments, context, info) {

return movies.find(movie => movie.id === movie.id);

}

}

}

You may notice that the resolver can accept some optional arguments. Let’s talk a bit about each of them:

  • parent: the result (or “resolution”) of the “parent” of the type that the current function will resolve
  • Arguments: the input parameters that the client sent
  • The context: an object that the GraphQL implementation provides to resolvers. The context can contain authentication or authorization data, or it can have references to external APIs, for example.
  • Information: an object that contains information relevant to resolving the type (not commonly used)
API development concept

Go further

What if we need to query a list of movies and then filter it? Let’s go back to the query type and add a new field:

type Query {

movie(id: ID!): Movie

films (director: director): [Movie]!

}

So now we can get a list of movies with the ability to filter by director. Note that filtering is optional in this case. The query would look like this:

request GetMoviesByDirector{

movies (director: “John Doe”) {

Title

year

}

}

And in the resolver the difference is that now we return the data using the filtered function instead of to find because now it’s a list of movies.

Complex filtering

You can also use what is called the input type. This contains all the necessary GraphQL filter options. So instead of creating multiple fields for filtering, we can have all filters in one type. Not clear? Take a look at the example below:

type MovieFilters = {

identifiers: [ID!]

director: director

}

type MoviesInput = {

filter: MovieFilters

}

type Query {

movie(id: ID!): Movie

movies (input: MoviesInput): [Movie]!

}

After that just change the resolver logic. Of course, it gets a bit more complex now. This is because instead of having a single type of GraphQL filter, the resolver must process the different types and return results for each. It may seem like a much more complex task, but it is not. Using JavaScript, simply identify the type of GraphQL filter to use. (This GraphQL filter will be passed in the args parameter.) We can now filter the two movies using ids and return a list of movies using the director as the filter.

At the end of the day

By adopting GraphQL in your applications, you will have a slightly slower learning curve at first. But quickly the added value of GraphQL is noticed. Back-end and front-end development becomes more agile and dynamic. And you will have fewer round trips. There are also many examples and cases to use as models.

The biggest difficulty of GraphQL is not in its implementation and its use but in its design. It doesn’t have the design issues of a REST application, but it brings new challenges nonetheless. There is still no widespread consensus on design patterns with GraphQL. There is a quality and versatility of GraphQL compared to REST solutions.

In this article, we have focused on one main point. However, GraphQL still provides many tools that, if used correctly, can make your API extremely efficient and save you development time and resources. Imagine the complexity of a front end needing to access several different APIs to obtain information. In a scenario like this, GraphQL works great.

Visit Traceable AI for more information on this and other issues. You can view webinars or watch a demo. There is also a useful blog.

This post was written by Rhuan Souza. A software engineer who has experience with infrastructure, Rhuan currently working as a full-stack web developer. He’s a passionate developer who not only focuses on code, but also wants to help change processes and make people’s lives easier.

The post How to Filter Using GraphQL: A Simple Tutorial appeared first on Traceable App & API Security.

*** This is a syndicated blog from the Security Bloggers Blog Network written by Rhuan Souza. Read the original post at: https://www.traceable.ai/blog-post/filter-using-graphql

Comments are closed.