Hubert
Hubert

Reputation: 495

How to negate a filter with JSONAPI requests in Drupal?

I'm trying to build a query that returns all items whose path do NOT contain a string.

I can easily build one that returns items whose path does contain a string:

GET /url?filter[path][CONTAINS]=string

But how can I negate that filter?

Upvotes: 2

Views: 2061

Answers (1)

jelhan
jelhan

Reputation: 6338

JSON:API specification itself is agnostic about the filtering strategy used. All it does is recommending that the query parameter filter is used for filtering:

Filtering

The filter query parameter is reserved for filtering data. Servers and clients SHOULD use this key for filtering operations.

Note: JSON:API is agnostic about the strategies supported by a server. The filter query parameter can be used as the basis for any number of filtering strategies.

https://jsonapi.org/format/#fetching-filtering

But you mentioned in a comment that you are using Drupal's JSON:API. That one implements a well specified filtering strategy.

The filtering strategy used by Drupal is build around conditions, which could be grouped and combined either with OR or AND.

A condition is the combination of a path of fields, an operator and a value. It's documentation lists the following operators as supported:

  • '=' (equal)
  • '<>' (not equal),
  • '>' (greater than)
  • '>=' (greater or equal than)
  • '<' (less than)
  • '<=' (less or equal than)
  • 'STARTS_WITH'
  • 'CONTAINS'
  • 'ENDS_WITH'
  • 'IN'
  • 'NOT IN'
  • 'BETWEEN'
  • 'NOT BETWEEN'
  • 'IS NULL'
  • 'IS NOT NULL'

For most operators it supports their negated counter part - like 'in' and 'not in', 'IS NULL' and 'IS NOT NULL', '<' and '>='. But a few operators do not have a negated counterpart: 'CONTAINS', 'STARTS_WITH' and ''ENDS_WITH'. I guess that's cause it may be very expensive to do a search with a 'NOT CONTAINS' operator on the supported databases.

As the documentation also doesn't mention a possibility to negate an condition or a group of conditions I think your specific use case is not support by Drupal's filtering strategy.

Upvotes: 3

Related Questions