Back to Blog
Lesson 25 of the REST API Design: Design Your First Clean REST API course
API ArchitectureAugust 11, 20263 min read

Implementing Query Logic in Task Manager

Master the implementation of combined filtering and sorting in your REST API. Learn to build a robust GET /v1/tasks endpoint for your Task Manager project.

REST APIBackend EngineeringNode.jsAPI DesignCoding Tutorial
Kanban board displayed on screen with charts and data analysis in modern office setup.

Previously in this course, we explored Introduction to Query Parameters and built the foundation for Filtering Collections. In this lesson, we are moving from theory to production-grade Implementation by combining those concepts within our Task Manager project to allow for simultaneous Filtering and Sorting.

The Logic Pipeline: From Query to Result

When a client sends a request to GET /v1/tasks?status=pending&sort=created_at:desc, the server needs to transform that string into a sequence of data operations. Think of this as a pipeline where the collection of all tasks passes through a series of "gates."

  1. Extraction: Pull the parameters from the request URL.
  2. Filtering: Apply logic to exclude records that don't match the criteria (e.g., status).
  3. Sorting: Reorder the remaining set based on the requested field.
  4. Response: Serialize the processed array into JSON.

Worked Example: Building the Controller Logic

In your TasksController, you shouldn't just dump the entire database into the response. Instead, you'll chain these operations. Here is how we implement this logic using a standard JavaScript/Node.js approach (you can apply this logic to any backend language):

JAVASCRIPT
// GET /v1/tasks?status=completed&sort=due_date:asc
router.get(CE9178">'/v1/tasks', (req, res) => {
  let tasks = [...database.tasks]; // Start with full collection

  // 1. Filtering Logic
  if (req.query.status) {
    tasks = tasks.filter(task => task.status === req.query.status);
  }

  // 2. Sorting Logic
  if (req.query.sort) {
    const [field, direction] = req.query.sort.split(CE9178">':');
    tasks.sort((a, b) => {
      if (direction === CE9178">'desc') {
        return new Date(b[field]) - new Date(a[field]);
      }
      return new Date(a[field]) - new Date(b[field]);
    });
  }

  // 3. Return the result
  res.status(200).json({ data: tasks });
});

Advancing the Task Manager Project

In your local repository, open your existing TasksController. Up until now, your route likely returned database.tasks directly. Replace that simple return with the pipeline pattern shown above.

Hands-on Exercise:

  1. Add a due_date field to your mock data in the database.js file if it doesn't exist.
  2. Implement the sorting logic in your GET /v1/tasks endpoint.
  3. Test it: Request /v1/tasks?status=pending to verify filtering, then append &sort=due_date:asc to see the combined result.

Common Pitfalls to Avoid

  • Mutating the Source: Notice in the code above I used [...database.tasks]. Never filter or sort your master data array directly, or you will accidentally delete tasks from your "database" for the next request. Always create a shallow copy first.
  • Case Sensitivity: Users might send ?status=Pending while your data stores it as pending. Always normalize your inputs using .toLowerCase() before comparing strings.
  • Invalid Sort Keys: What happens if a user requests ?sort=invalid_field:asc? Your code will likely crash. Always add a validation check to ensure the requested field exists in your task model.

FAQ: Query Logic Implementation

Q: Should I handle all sorting on the server or the client? A: Always on the server. If you have 10,000 tasks, sending them all to the client just so they can sort them will destroy your performance and waste bandwidth.

Q: How do I handle multiple sort parameters? A: You can implement a comma-separated string (e.g., sort=status:asc,due_date:desc). Split the string by the comma, iterate through the segments, and apply the sorting logic sequentially.

Q: Is it better to filter via URL parameters or a JSON body? A: For GET requests, always use URL parameters (query strings). GET requests are intended to be cacheable and bookmarkable, and they do not support request bodies in most standard implementations.

Recap

We have successfully moved from basic routing to a flexible data retrieval pipeline. By implementing Filtering and Sorting within our GET /v1/tasks endpoint, we’ve made our Task Manager API significantly more useful for real-world clients. This pattern of composing operations is the cornerstone of professional Implementation in RESTful services.

Up next: Need for Pagination — we'll learn why returning "all" tasks is a recipe for disaster in production.

Similar Posts