What Are Query Parameters?
Query parameters are key-value pairs appended to the end of an API URL to modify or filter the response. They are introduced by a ?
in the URL and separated by an &
when there are multiple parameters. Query parameters are flexible and provide a way to pass information without altering the endpoint structure.
For example:
GET /api/products?category=electronics&price=low
In this URL:
- category=electronics specifies the product category.
- price=low filters products by price.
How Query Parameters Work
- Key-Value Pairs: Each query parameter consists of a key and a value. The key defines the parameter’s purpose, and the value provides the data.
- URL Structure: Query parameters are always appended to the base URL after a
?
. Additional parameters are joined using&
. - Server Interpretation: The server processes these parameters to customize the response, such as filtering, sorting, or limiting the results.
Use Cases for Query Parameters
- Filtering Data: Query parameters help filter results based on specific criteria.
- Example: GET /api/users?role=admin retrieves all users with the role of “admin.”
- Sorting Data: Parameters can determine the order of results.
- Example: GET /api/products?sort=price_asc sorts products by ascending price.
- Pagination: Query parameters specify the page number and page size for paginated data.
- Example: GET /api/orders?page=2&limit=10 retrieves the second page of orders with 10 items per page.
- Searching: Parameters can include search terms.
- Example: GET /api/posts?query=technology retrieves posts related to “technology.”
- Configuring Responses: Query parameters can control the amount or type of data returned.
- Example: GET /api/posts?fields=title,author retrieves only the title and author fields for posts.
Implementing Query Parameters
Let’s explore how to handle query parameters in APIs using Node.js with Express.
Example 1: Basic Query Parameters
const express = require('express');
const app = express();
app.get('/api/products', (req, res) => {
const category = req.query.category;
const price = req.query.price;
const products = [
{ id: 1, name: 'Laptop', category: 'electronics', price: 'high' },
{ id: 2, name: 'Shoes', category: 'fashion', price: 'low' },
];
let filteredProducts = products;
if (category) {
filteredProducts = filteredProducts.filter(product => product.category === category);
}
if (price) {
filteredProducts = filteredProducts.filter(product => product.price === price);
}
res.json({
data: filteredProducts,
message: 'Filtered products fetched successfully',
});
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Explanation:
- The req.query object extracts query parameters from the URL.
- The category and price parameters filter the products array.
- The response returns only the filtered products.
Example 2: Handling Multiple Parameters
app.get('/api/users', (req, res) => {
const { role, status, sort } = req.query;
const users = [
{ id: 1, name: 'John', role: 'admin', status: 'active' },
{ id: 2, name: 'Jane', role: 'user', status: 'inactive' },
];
let filteredUsers = users;
if (role) {
filteredUsers = filteredUsers.filter(user => user.role === role);
}
if (status) {
filteredUsers = filteredUsers.filter(user => user.status === status);
}
if (sort === 'name_asc') {
filteredUsers.sort((a, b) => a.name.localeCompare(b.name));
}
res.json({
data: filteredUsers,
message: 'Filtered users fetched successfully',
});
});
Explanation:
- This example shows how to handle multiple query parameters like role, status, and sort.
- The sort parameter orders users alphabetically by name.
Best Practices for Working with Query Parameters
- Validation: Validate query parameters to prevent invalid or malicious inputs.
- Use libraries like Joi or custom middleware for validation.
- Default Values: Provide default values for optional parameters.
- Example: Set a default limit for pagination if not provided.
- Documentation: Clearly document supported query parameters for each endpoint.
- Example: Use tools like Swagger to generate API documentation.
- Consistent Naming: Use consistent and meaningful names for query parameters.
- Example: Use page instead of ambiguous names like p.
- Error Handling: Return appropriate error messages for invalid or missing parameters.
- Example: Respond with 400 Bad Request for malformed queries.
Common Challenges
- Complex Queries: Handling multiple parameters can become complex if not properly structured.
- Performance: Filtering and sorting large datasets on the server side may affect performance.
- Security Risks: Query parameters can expose sensitive information if not encrypted or validated.