(Beginner) How to filter by field when fetching data

Hi there!

Just started learning APIs and Cockpit. I was wondering how can you filter what to look for in the API.
I previously only used SQL for this type of thing, and can’t quite workout how to apply these filters while using curl and getting my data.

My search looks like this at the moment

/api/collections/get/maps

which returns all the maps in the database, now let’s say I have a field called “Category” and I wanted to search for a “Horror” category. I tried few iterations of this, but can’t seem to get it right.

/api/collections/get/maps?Category=Horror

This still retuns all the maps. What am I doing wrong?

For sake of simplicity let’s say the JSON looks like this:

{
  "fields": {
    "MapName": {
      "name": "MapName",
      "type": "text",
      "localize": false,
      "options": [
        
      ]
    },
    "Category": {
      "name": "Category",
      "type": "text",
      "localize": false,
      "options": [
        
      ]
  },
  "entries": [
    {
      "MapName": "Riddleman",
      "Category": "Puzzle",
      ],
      "_mby": "cc16c9b9396362df7b00031e",
      "_by": "cc16c9b9396362df7b00031e",
      "_modified": 1638947411,
      "_created": 1637146888,
      "_id": "c796554f666437108c0001e3",
    },
    {
      "MapName": "Super Cool Map",
      "Category": "Horror",
      },
      "_mby": "cc16c9b9396362df7b00031e",
      "_by": "cc16c9b9396362df7b00031e",
      "_modified": 1638947440,
      "_created": 1638947440,
      "_id": "f8ccb99f616363f7cd000213"
    }
  ],
  "total": 2
}

Hiya,

Try adding in a filter to your API fetch:

In the fetch URL params:

/api/collections/get/maps?token=xxx&filter[category]=horror

Or in the body:

  fetch("/api/collections/get/maps?token=xxx",{
        method: "post",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          filter: { category: "horror" },
        }),
      }
    )
      .then((res) => {
        return res.json();
      })
      .then((res) => {
        console.log(res.entries);
      });

You can also sort entries by name, date etc in the same way. You can see more options in the docs here.

Hope this helps!

1 Like

Thanks so much! I knew it had to be something like this, just couldn’t quite get it right. Much appreciated!