Query Parameter Fundamentals
Query parameters allow clients to modify API requests without changing the resource path. They're essential for filtering, sorting, and customizing responses.
What Are Query Parameters?
Query parameters appear after the ? in a URL:
/api/users?status=active&role=admin
└──────────────────────┘
Query parameters
Multiple parameters are separated by &.
Common Use Cases
1. Filtering
GET /api/products?category=electronics
GET /api/orders?status=pending&minTotal=100
2. Sorting
GET /api/products?sort=price
GET /api/products?sort=-createdAt # Descending
3. Pagination
GET /api/users?page=2&limit=20
GET /api/users?offset=40&limit=20
4. Field Selection
GET /api/users?fields=id,name,email
5. Search
GET /api/products?q=laptop
GET /api/products?search=gaming+laptop
Query Parameter Naming
Use Snake Case or Camel Case Consistently
# Snake case (common)
GET /api/users?created_after=2024-01-01&max_results=10
# Camel case (also common)
GET /api/users?createdAfter=2024-01-01&maxResults=10
Use Clear, Descriptive Names
# Bad
GET /api/products?c=electronics&s=price
# Good
GET /api/products?category=electronics&sort=price
Handling Multiple Values
Repeated Parameters
GET /api/products?category=electronics&category=accessories
Comma-Separated
GET /api/products?categories=electronics,accessories
Array Bracket Syntax
GET /api/products?category[]=electronics&category[]=accessories
Exercise: Parse Query Parameters
Loading JavaScript Exercise...
URL Encoding
Special characters must be URL-encoded:
| Character | Encoded |
|---|---|
| Space | %20 or + |
| & | %26 |
| = | %3D |
| ? | %3F |
| / | %2F |
GET /api/search?q=C%2B%2B # Searching for "C++"
GET /api/users?name=John%20Doe # Name with space
Best Practices
- Document all parameters - Make it clear what each parameter does
- Provide defaults - Don't require all parameters
- Validate values - Return 400 for invalid parameters
- Ignore unknown parameters - For forward compatibility
- Use consistent naming - Same style throughout your API
Reserved vs Custom Parameters
Common Reserved Names
page, limit, offset # Pagination
sort, order # Sorting
fields, include # Field selection
q, search, query # Search
Custom Parameters
GET /api/orders?status=pending&customerId=123
Summary
| Use Case | Example |
|---|---|
| Filtering | ?status=active&type=premium |
| Sorting | ?sort=name&order=asc |
| Pagination | ?page=2&limit=20 |
| Field selection | ?fields=id,name |
| Search | ?q=keyword |
Query parameters are essential for building flexible, powerful APIs that clients can customize to their needs.

