Python Friday #222: Filter the Tasks in the FastAPI Application

The to-do application started nicely and with the refactoring we got the most obvious code smells fixed. While checking the API in uvicorn, I noticed three missing features that we are going to implement in this post.

This post is part of my journey to learn Python. You find the code for this post in my PythonFriday repository on GitHub.

 

Show all existing tasks

So far, we can create, read, update, and delete a single task. But we cannot get back all the tasks currently in our application. Once more we start with a failing test to drive our development:

With this test in place, we can create our endpoint:

 

Filter the tasks

The longer we run our application, the more tasks it will collect. It would be nice if we could filter our tasks to only get back the ones that are not done yet. Our test for this new feature can look like this:

Filters are a topic that usually starts small and then grows. We therefore better look at a solution that we can extend should the need arise. With the feature of Dependency Injection in FastAPI we can create a function that accepts our filter, wraps it into the right data type and then hands it as a dictionary to our endpoint:

For the time being, we keep the filter logic in the endpoint. When we move to SQLAlchemy, we can use a filter plug-in that allows us to filter inside the database and so reduce the workload for our application.

With our first filter in place, another idea pops up. Would it not be nice to get back only tasks that are due up to a certain date? Let us write the test so that we can see what we expect:

We can add another parameter to our filter function and then use the filter inside our endpoint. Since Pydantic and FastAPI convert our due_before parameter into a date object, we do not need to convert it:

 

Remove the error message at the / route

If we open our API in a browser without specifying a route, we get this error message:

In the browser we get a JSON snippet that tells us detail: Not Found

While our API works, this is not a nice way to greet our users. Before we add another endpoint, we write a small test to drive the behaviour:

We can write this show_root() method to make the test pass:

If we now open the API without a specific route, we get this message instead of an error:

Instead of the error message, we now get message 'The minimalistic ToDo API'

 

Next

With the addition of the above features, we now have everything in place to work with our to-do’s. However, as always there is another thing that pops up as soon as a real user tries to work with the API: We do not have any useful data validation. Next week we improve our models to be more specific on what we accept.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.