Skip to main content
RESTful Principles
CHAPTER 11 Beginner

Query Parameters and Filtering

Updated: May 13, 2026
5 min read

# CHAPTER 11

Query Parameters and Filtering

1. Introduction

In the last chapter, we established that endpoints like /users should return a list of users. However, what if your database has 10 million users? Returning all of them at once will crash your server and the client's browser. We need a way to filter, search, and limit this data. In Chapter 11, we will explore Query Parameters—the key-value pairs at the end of a URL—and how to use them to create dynamic, searchable APIs.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Identify query parameters in a URL string.
  • Differentiate between path parameters (URLs) and query parameters.
  • Use query parameters to filter data in a REST API.
  • Implement basic dynamic SQL queries based on query strings.
  • Understand the security implications of user-provided query data.

3. Beginner-Friendly Explanation

Imagine going to a massive shoe store. The endpoint /shoes is like walking in and saying, "Show me every shoe in the store." You will be overwhelmed. Instead, you might say: "Show me shoes that are *size 10*, *color red*, and *brand Nike*."

In a URL, this translates to: /shoes?size=10&color=red&brand=nike

The ? marks the beginning of the query string. The & separates different filters. These are Query Parameters. They don't change *what* resource you are looking for (shoes), they just narrow down the results.

4. Real-World Examples

  • E-Commerce: Searching for a laptop under $1000: /products?category=laptops&maxprice=1000
  • Social Media: Finding active users in London: /users?location=london&status=active
  • Analytics: Fetching data between two dates: /sales?startdate=2023-01-01&enddate=2023-12-31

5. Detailed Code Examples

In PHP, query parameters are automatically populated into the $
GET superglobal array.
php
1234567891011121314151617181920212223242526272829
<?php
// API Endpoint: /users

// 1. Get the query parameters, set defaults if not provided
$status = $_GET[&#039;status'] ?? 'all';
$role = $_GET[&#039;role'] ?? 'all';

// 2. Base SQL Query
$sql = "SELECT id, name, status, role FROM users WHERE 1=1";
$params = [];

// 3. Dynamically build the query based on filters
if ($status !== &#039;all') {
    $sql .= " AND status = :status";
    $params[&#039;:status'] = $status;
}

if ($role !== &#039;all') {
    $sql .= " AND role = :role";
    $params[&#039;:role'] = $role;
}

// 4. Execute (using PDO to prevent SQL injection)
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);

echo json_encode($users);
?>

6. Request/Response Examples

When a client sends a filtered request, the response structure remains the same, just with fewer results.

Request:

http
12
GET /articles?author_id=5&published=true HTTP/1.1
Host: api.blog.com

Response:

json
12345678
[
  {
    "id": 101,
    "title": "REST API Basics",
    "author_id": 5,
    "published": true
  }
]

7. HTTP Examples

A common point of confusion is when to use a URL Path vs a Query Parameter.
  • Path Parameter: Used to identify a *specific* resource.
  • Correct: /users/5
  • Incorrect: /users?id=5
  • Query Parameter: Used to sort, filter, or limit a *collection* of resources.
  • Correct: /users?role=admin
  • Incorrect: /users/role/admin

8. JSON Examples

When returning filtered data, it is often helpful to echo back the filters applied so the client can verify the state.
json
12345678910111213
{
  "meta": {
    "total_results": 15,
    "filters_applied": {
      "role": "admin",
      "status": "active"
    }
  },
  "data": [
    {"id": 4, "name": "Admin User 1"},
    {"id": 8, "name": "Admin User 2"}
  ]
}

9. Best Practices

  • Use standard naming: Keep parameter names simple and lowercase (e.g., ?minprice=10, not ?MinimumPriceValue=10).
  • Support multiple values: If a user wants to filter by multiple colors, support comma-separated values: ?colors=red,blue,green.
  • Always use Prepared Statements: Never insert $GET variables directly into your SQL string. Always use parameterized queries (PDO) to prevent SQL Injection.

10. Common Mistakes

  • Ignoring Validation: Just because a user passes ?age=twenty, doesn't mean your database will accept a string. Always validate and sanitize query parameters before processing them in PHP.
  • Overcomplicating filters: Creating massive, complex JSON filter objects and trying to pass them via GET requests (which have URL length limits). If filtering becomes extremely complex, some APIs switch to using a POST /search endpoint with a JSON body.

11. Mini Exercises

  1. 1. Look at this URL: https://api.weather.com/forecast?city=london&days=3. What are the keys and values of the query parameters?
*(Answer: city = london, days = 3)*

12. Coding Challenges

Challenge 1: Write a PHP snippet that checks if $GET['category'] exists. If it does, create a PDO prepared statement to fetch products matching that category. If it doesn't, fetch all products.

13. MCQs with Answers

Question 1

Where do query parameters appear in an HTTP request?

Question 2

Which PHP array automatically holds the values of query parameters?

Question 3

When should you use a Path Parameter instead of a Query Parameter?

14. Interview Questions

  • Q: Explain the difference between a Path parameter and a Query parameter, and when to use each.
  • Q: How do you safely use query parameters in a database query without exposing your API to SQL injection?
  • Q: What happens if a client passes a query parameter that your API does not recognize (e.g., ?fakeparam=true)? How should the API handle it?

15. FAQs

Q: Can I use query parameters with POST or PUT requests? A: Yes, you can (e.g., POST /users?notify=true). However, it is generally preferred to put data and instructions inside the JSON body for POST/PUT requests to keep the URL clean.

Q: Is there a limit to how many query parameters I can add? A: Technically no, but browsers and web servers have maximum URL length limits (usually around 2000 characters). If your query string is getting that long, you should rethink your design.

16. Summary

In Chapter 11, we learned that Query Parameters are the standard way to pass filters and search terms to a REST API collection endpoint. We differentiated them from Path Parameters, learned how to capture them in PHP using $_GET, and explored how to dynamically build safe database queries to return tailored results.

17. Next Chapter Recommendation

Filtering data is only half the battle when dealing with large databases. We also need to chop the data into manageable pages. Proceed to Chapter 12: Pagination, Sorting, and Searching to complete our mastery of collection endpoints.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·