APIs Query Parameters

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

  1. 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.
  2. URL Structure: Query parameters are always appended to the base URL after a ?. Additional parameters are joined using &.
  3. Server Interpretation: The server processes these parameters to customize the response, such as filtering, sorting, or limiting the results.

Use Cases for Query Parameters

  1. 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.”
  2. Sorting Data: Parameters can determine the order of results.
    • Example: GET /api/products?sort=price_asc sorts products by ascending price.
  3. 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.
  4. Searching: Parameters can include search terms.
    • Example: GET /api/posts?query=technology retrieves posts related to “technology.”
  5. 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

  1. Validation: Validate query parameters to prevent invalid or malicious inputs.
    • Use libraries like Joi or custom middleware for validation.
  2. Default Values: Provide default values for optional parameters.
    • Example: Set a default limit for pagination if not provided.
  3. Documentation: Clearly document supported query parameters for each endpoint.
    • Example: Use tools like Swagger to generate API documentation.
  4. Consistent Naming: Use consistent and meaningful names for query parameters.
    • Example: Use page instead of ambiguous names like p.
  5. Error Handling: Return appropriate error messages for invalid or missing parameters.
    • Example: Respond with 400 Bad Request for malformed queries.

Common Challenges

  1. Complex Queries: Handling multiple parameters can become complex if not properly structured.
  2. Performance: Filtering and sorting large datasets on the server side may affect performance.
  3. Security Risks: Query parameters can expose sensitive information if not encrypted or validated.

Leave a Comment

BoxofLearn