Filtering, Sorting, and Paging for ASP.NET Core REST APIs Part 1
Learn how to easily filter, sort, and page your data without bothering about the complexities of writing your own library.
En route building robust Restful APIs, one thing you cannot avoid is filtering, sorting and paging. Why? You may ask. Have you thought about making a GET request to an endpoint and having loads of data returned? This may not suit your business requirement and if too many requests are made to that endpoint, fetching all that data could greatly impact the server performance. Wouldn’t it be nice to filter your GET requests so you have just the data you need?
On my quest to solving this business problem, I came across some great libraries for filtering, sorting and paging. Sieve stands out for me. With Sieve you don’t have to reinvent the wheels as you can customize your filtering, sorting and paging needs.
Firstly, you create a simple ASP.NET Core Web API project using Visual Studio. I’ll be using .NET 5 and it has built in, Swagger for API Documentation.
Next, you add a Models folder to the project and create a Student class inside of the folder.
Inside the Student class you add the following properties.
Go ahead and add another folder to the project titling it Database, then create a StudentDb class, this would serve as our mock database for fetching data.
Inside the Controllers folder add a StudentController API Controller Item.
Add the Sieve nuget package to the project.
Inside the StudentController, create a constructor that would allow you inject the necessary services in the DI (Dependency Injection) Container.
Before any of the service added to the StudentController constructor can run they have to be configure in the DI container in the Startup.cs class.
Before we can successfully use Sieve in our project, some data attribute has to be added to the model properties users intend to perform filtering operation on.
Go ahead to create GET request endpoint after which you can apply the Sieve library method, this performs the filtering, sorting and paging.
That’s was easy you know!
Run the project.
Without specifying any terms in the query, we get all the data in the mock db
Let’s try filtering names.
Sort all the ages in ascending order.
Let’s try the paging feature.
From the query above you can see that the data was subdivided into three pages and the page number we are on is two.
This is just a very basic example of the capabilities of Sieve.
You can also use Fluent API in Sieve to do separation of concerns in the advent you don’t want to pollute your model classes or you working with inherited classes. I found it useful while working with ASP.NET Identity model classes.
In the sequel of the article we would look at customizing our Filtering, Sorting, and Paging.
You can check Sieve documentation on Github to better explore and see its full capabilities.
Another great library for Filtering, Sorting, Paging in ASP.NET Core is FOP.