Get the FREE Ultimate OpenClaw Setup Guide →

api-filtering-sorting

npx machina-cli add skill secondsky/claude-skills/api-filtering-sorting --openclaw
Files (1)
SKILL.md
2.3 KB

API Filtering & Sorting

Build flexible filtering and sorting systems that handle complex queries efficiently.

Query Parameter Syntax

GET /products?category=electronics&price[gte]=100&price[lte]=500&sort=-price,name

Implementation (Node.js)

const allowedFilters = ['category', 'status', 'price', 'createdAt'];
const allowedSorts = ['name', 'price', 'createdAt'];

app.get('/products', async (req, res) => {
  const filter = {};
  const sort = {};

  // Parse filters
  for (const [key, value] of Object.entries(req.query)) {
    if (key === 'sort') continue;

    const match = key.match(/^(\w+)\[(\w+)\]$/);
    if (match) {
      const [, field, operator] = match;
      if (!allowedFilters.includes(field)) continue;
      filter[field] = { [`$${operator}`]: parseValue(value) };
    } else if (allowedFilters.includes(key)) {
      filter[key] = value;
    }
  }

  // Parse sort
  if (req.query.sort) {
    for (const field of req.query.sort.split(',')) {
      const direction = field.startsWith('-') ? -1 : 1;
      const name = field.replace(/^-/, '');
      if (allowedSorts.includes(name)) sort[name] = direction;
    }
  }

  const products = await Product.find(filter).sort(sort);
  res.json({ data: products });
});

function parseValue(value) {
  if (value === 'true') return true;
  if (value === 'false') return false;
  if (!isNaN(value)) return Number(value);
  return value;
}

Filter Operators

OperatorMeaningExample
eqEquals?status=active
neNot equals?status[ne]=deleted
gt/gteGreater than?price[gte]=100
lt/lteLess than?price[lte]=500
inIn array?status[in]=active,pending
likeContains?name[like]=phone

Security

  • Whitelist allowed filter fields
  • Validate input types per field
  • Index frequently-filtered columns
  • Limit query complexity
  • Prevent SQL/NoSQL injection

Best Practices

  • Support common operators
  • Cache filter option lists
  • Monitor query performance
  • Provide sensible defaults

Source

git clone https://github.com/secondsky/claude-skills/blob/main/plugins/api-filtering-sorting/skills/api-filtering-sorting/SKILL.mdView on GitHub

Overview

Build flexible filtering and sorting systems that handle complex queries efficiently. Use when implementing search endpoints, building data grids, or creating dynamic query APIs.

How This Skill Works

Define allowedFilters and allowedSorts, parse query parameters into a filter object and a sort object, map operators to Mongo-like $ operators, and execute a database query. Values are parsed with a helper to convert booleans, numbers, and strings before filtering.

When to Use It

  • Implementing search endpoints with multi-criteria filtering
  • Server-side filtering for data grids and dashboards
  • Creating dynamic query APIs that expose flexible filters and sorts
  • Enforcing security by whitelisting fields and validating input
  • Optimizing performance with indexed filters and query caching

Quick Start

  1. Step 1: Define allowedFilters and allowedSorts in your route.
  2. Step 2: Parse req.query to build filter and sort objects, using the regex for [] operators.
  3. Step 3: Run the query (e.g., Product.find(filter).sort(sort)) and return results, with a parseValue helper to normalize types.

Best Practices

  • Support common operators
  • Cache filter option lists
  • Monitor query performance
  • Provide sensible defaults
  • Index frequently-filtered columns

Example Use Cases

  • GET /products?category=electronics&price[gte]=100&price[lte]=500&sort=-price,name
  • Filter by status with in operator and sort by createdAt
  • Search by name using like operator: ?name[like]=phone
  • Multi-field sorting: sort=name,-createdAt
  • Filter by boolean and range: ?active=true&price[lt]=1000

Frequently Asked Questions

Add this skill to your agents
Sponsor this space

Reach thousands of developers