Filtering Tasks by Status
Introduction: The Need for Filtering Tasks
Welcome back! So far, you have learned how to organize your backend code, validate data, and secure your Task Manager API. Now, let’s make your API even more useful by allowing users to filter tasks based on whether they are completed.
Imagine you have a long list of tasks. Sometimes, you only want to see what’s left to do, and other times, you want to review what you’ve already finished. Filtering tasks by their completion status makes this possible. In this lesson, you will learn how to add this feature to your API.
Service Layer Overview: Filtering Logic
Let’s quickly go through the service functions you'll use to implement filtering.
In your taskService.ts, you have:
Here’s what each one does:
getAllTasks()returns every task in your in-memory list.filterTaskByStatus(completed)returns only the tasks that match the completed status (true or false).
Using Query Parameters to Filter API Results
To let users choose which tasks they want to see, you will use something called a query parameter. Query parameters are extra pieces of information added to the end of a URL. They help you filter or sort data when making API requests.
For example, if you want to see only completed tasks, you might use a URL like this:
Here, completed is the query parameter, and true is its value. If you want to see only incomplete tasks, you would use:
Your API will read this parameter and use it to decide which tasks to return. This type of filtering is stateless — the client decides what it wants to see (completed=true or false), and the API responds accordingly without needing to track user sessions or state.
Building the Filter Endpoint
Now, let’s build the endpoint that filters tasks by their completion status. Here is the code for the filter endpoint:
Let’s break down what’s happening here:
-
Reading the Query Parameter
The code gets the value of thecompletedquery parameter from the request URL:TypeScriptIf the parameter is missing, it returns an error.
-
Validating the Parameter
The code checks if the value is eithertrueorfalse. If not, it returns an error message:TypeScript -
Filtering the Tasks
The code converts the string to a boolean and uses the service function to filter tasks:TypeScript -
Returning the Result
Finally, it returns the filtered list of tasks in a success response.
Example Output:
If you call /api/tasks/filter?completed=true, you might get a response like:
If you call /api/tasks/filter?completed=false, you’ll get only the tasks that are not completed.
