0
0
ExpressHow-ToBeginner · 4 min read

How to Implement Filtering in Express API Easily

To implement filtering in an Express API, use query parameters from req.query to get filter criteria and apply them to your data source before sending the response. This lets clients request only the data they want by specifying filters in the URL.
📐

Syntax

Filtering in Express API typically uses query parameters accessed via req.query. You read these parameters and use them to filter your data before sending it back.

  • req.query: Object containing URL query parameters.
  • Filter keys: Names of parameters clients send to filter data.
  • Filter logic: Code that applies these filters to your data source.
javascript
app.get('/items', (req, res) => {
  const filters = req.query;
  // Use filters to select data
  res.send(filteredData);
});
💻

Example

This example shows an Express API endpoint that filters a list of items by category and maxPrice using query parameters.

javascript
import express from 'express';
const app = express();

const items = [
  { id: 1, name: 'Apple', category: 'fruit', price: 1 },
  { id: 2, name: 'Carrot', category: 'vegetable', price: 2 },
  { id: 3, name: 'Banana', category: 'fruit', price: 1.5 },
  { id: 4, name: 'Broccoli', category: 'vegetable', price: 3 }
];

app.get('/items', (req, res) => {
  const { category, maxPrice } = req.query;
  let filteredItems = items;

  if (category) {
    filteredItems = filteredItems.filter(item => item.category === category);
  }

  if (maxPrice) {
    const max = parseFloat(maxPrice);
    filteredItems = filteredItems.filter(item => item.price <= max);
  }

  res.json(filteredItems);
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
Output
GET /items?category=fruit&maxPrice=1.5 [ { "id": 1, "name": "Apple", "category": "fruit", "price": 1 }, { "id": 3, "name": "Banana", "category": "fruit", "price": 1.5 } ]
⚠️

Common Pitfalls

Common mistakes when implementing filtering include:

  • Not parsing query parameters correctly (e.g., treating numbers as strings).
  • Ignoring missing or invalid filter values, causing errors or wrong results.
  • Filtering data inefficiently, especially with large datasets.
  • Not validating or sanitizing input, which can lead to security issues.

Always parse and validate query parameters before using them.

javascript
/* Wrong way: Using query params without parsing */
app.get('/items', (req, res) => {
  const maxPrice = req.query.maxPrice;
  const filtered = items.filter(item => item.price <= maxPrice); // maxPrice is string, causes wrong filtering
  res.json(filtered);
});

/* Right way: Parse maxPrice to number */
app.get('/items', (req, res) => {
  const maxPrice = parseFloat(req.query.maxPrice);
  if (isNaN(maxPrice)) {
    return res.status(400).send('Invalid maxPrice');
  }
  const filtered = items.filter(item => item.price <= maxPrice);
  res.json(filtered);
});
📊

Quick Reference

Tips for filtering in Express API:

  • Use req.query to access filters.
  • Parse and validate query parameters.
  • Apply filters to your data source before responding.
  • Return filtered data as JSON.
  • Handle missing or invalid filters gracefully.

Key Takeaways

Use req.query to get filter criteria from URL query parameters.
Always parse and validate query parameters before filtering data.
Apply filter logic to your data source before sending the response.
Handle missing or invalid filters to avoid errors.
Return filtered results as JSON for easy client use.