Query Parameters and Filtering
# 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.
6. Request/Response Examples
When a client sends a filtered request, the response structure remains the same, just with fewer results.Request:
Response:
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.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
$GETvariables 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 /searchendpoint with a JSON body.
11. Mini Exercises
-
1.
Look at this URL:
https://api.weather.com/forecast?city=london&days=3. What are the keys and values of the query parameters?
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
Where do query parameters appear in an HTTP request?
Which PHP array automatically holds the values of query parameters?
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.