Skip to content

Filtering Collection Resources

  • Common Use Cases: For example, if you have an API that returns a list of species, you might want to filter this list based on parameters such as habitat, family, conservation status, or region.


How to Implement Filtering in RESTful Web Services?

Section titled “How to Implement Filtering in RESTful Web Services?”
  • Resource Identification: Determine which resource the filtering applies to. For example, if you have a species resource, the endpoint might be /species.
  • Filtering Parameters: Decide on the parameters that clients can use to filter the data. These parameters could include various fields of the resource such as IDs, dates, names, or any other attributes relevant to your application.

Common Filter Types:

  • Exact Match: status=active, category=electronics
  • Range Queries: price_min=10&price_max=100, date_after=2023-01-01
  • Pattern Matching: name_contains=smartphone, email_ends_with=@company.com
  • List Membership: category_in=electronics,books,clothing

Modify your API endpoints to accept filter parameters. Typically, filtering parameters are passed as query parameters in the URI of the GET request.

Example URI for filtering:

Terminal window
GET /api/species?habitat=forest&family=Felidae&conservation_status=endangered
batch

In this example:

  • habitat filters species by their natural habitat.
  • family filters species by their taxonomic family.
  • conservation_status filters species by their conservation status.

3. Implement Filtering Logic on the Server Side:

Section titled “3. Implement Filtering Logic on the Server Side:”
  • Extract Parameters: Parse the query parameters from the request.
  • Validate Parameters: Ensure that the parameters are valid and sanitize them to prevent issues such as SQL injection or other security vulnerabilities.
  • Apply Filtering: Use the parameters to filter the data. This usually involves:
  • Querying the database with filtering conditions.
  • Iterating over a collection of objects and applying filter logic programmatically.

For example, in SQL, you might use:

SELECT * FROM species WHERE habitat = 'forest' AND family = 'Felidae' AND conservation_status = 'endangered';
sql
  • Querying the database with filtering conditions.
  • Or, iterating over a collection of objects and applying filter logic programmatically.

For example, in SQL, you might use:

SELECT * FROM species WHERE habitat = 'forest' AND family = 'Felidae' AND conservation_status = 'endangered';
sql
  • Return the filtered data: Respond with the filtered data in the appropriate format (e.g., JSON or XML). Ensure that the response contains only the data that matches the criteria specified.

Example 1: Filtering with Multiple Criteria

Section titled “Example 1: Filtering with Multiple Criteria”
  1. API endpoint: /species
  2. Filter parameters: habitat, population_range (min and max), conservation_status
  3. PHP Implementation:
<?php
// Database connection
$dsn = 'mysql:host=localhost;dbname=wildlife';
$username = 'root';
$password = '';
$options = [];
$pdo = new PDO($dsn, $username, $password, $options);
// Extract and validate filter parameters
$habitat = isset($_GET['habitat']) ? $_GET['habitat'] : '';
$min_population = isset($_GET['min_population']) ? (int)$_GET['min_population'] : 0;
$max_population = isset($_GET['max_population']) ? (int)$_GET['max_population'] : PHP_INT_MAX;
$conservation_status = isset($_GET['conservation_status']) ? $_GET['conservation_status'] : '';
// Build the SQL query
$sql = "SELECT * FROM species WHERE population BETWEEN :min_population AND :max_population";
$params = [
':min_population' => $min_population,
':max_population' => $max_population
];
if (!empty($habitat)) {
$sql .= " AND habitat = :habitat";
$params[':habitat'] = $habitat;
}
if (!empty($conservation_status)) {
$sql .= " AND conservation_status = :conservation_status";
$params[':conservation_status'] = $conservation_status;
}
// Prepare and execute the query
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$species = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Return the results as JSON
header('Content-Type: application/json');
echo json_encode($species);
?>
php