neomerx / json-api

Framework agnostic JSON API (jsonapi.org) implementation

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Example for filtering

danDanV1 opened this issue · comments

commented

Could I Kindly ask for an example of how to implement filtering based on property value?

api.com/foods?filter[category]=vegetable

Given the following models:

{
"name": "apple"
"category":"fruit"
},
{
"name": "carrot"
"category":"vegetable"
}

and have the output only return the carrot model.

EncodingParameters seems to be the place to start. I've got my includes function working just fine there, but documentation is sparse and am not sure how to do the filtering.

As I can see you're only starting with JSON API so before answering the question I'll make a few changes in the question itself.

Data Format

The models in JSON API format might look like

{
  "data": [
    {
      "type": "products",
      "id": "1",
      "attributes": {
        "name": "apple"
      },
      "relationships": {
        "category": { "type": "categories", "id": "fruit" }
      }
    }, {
      "type": "products",
      "id": "2",
      "attributes": {
        "name": "carrot"
      },
      "relationships": {
        "category": { "type": "categories", "id": "vegetable" }
      }
    }
  ]
}

The difference is that IDs are added and relationships between other entities such as Categories made more clear.

Query Format

Filtering syntax such as filter[category]=vegetable is outside of JSON API specification scope so it's up to developers to decide which operations (==, !=, >, < and etc) to support and if conditions in relationships such as product -> category -> id == vegetable to support as well.

What is the process overall and what is the scope of this library

Overall the process might look like

  • receive request
  • authenticate user
  • validate and parse query parameters, build SQL, query database
  • convert data from PHP objects to string in JSON API format
  • return response

This library covers only the part in bold.

Thus there are a couple of options

  • integrate the library with a framework of your choice
  • use a framework which already has integration with the library such as Limoncello which has it all including auth/validation/data migrations/filtering/sorting/etc. The project main page has a link on 6 min video so you can get the idea. Also @lindyhopchris develops laravel based project with similar goals.

If you run Limoncello demo app you can see how filtering works. Here a couple of screenshots. The first one shows an unfiltered list of users and the second one shows with a filter applied (see URL)

image

I have a feeling I've answered your question. If you have any further questions please don't hesitate to ask.

commented

Thanks very much for your detailed and thorough response. This will help get me going in the right direction.