Sorting Resources on your ASP NET Core Web API

Sorting Resources on your ASP NET Core Web API
Photo by Jan Antonin Kolar / Unsplash

Hello my fellow developers, here we are on a new part of this Web API Development series, we continue with exciting topics like the last post about Filtering Data in our API. Today we will be learning about sorting resources on our API, the effect it can have in our systems, and the benefits that provides for the client. I’ll teach you how you can sort your API resources and also will provide some useful code examples for you to follow along. So without further ado let’s get our hands on the code!

The Importance of Sorting Resources on API

Sorting resources on an API is crucial for several reasons. Firstly, it enhances the user experience by making it easy to find information. By sorting resources, users do not have to scroll through pages of irrelevant information to find what they are looking for. Instead, they can quickly find the information they need and move on to other tasks.

Secondly, sorting resources on an API improves the performance of the application. By reducing the amount of data that needs to be loaded, the application loads faster, leading to a better user experience.

Thirdly, sorting resources on an API makes it easier for developers to maintain the application. When resources are sorted, developers can easily locate specific data and make changes where necessary.

How to Sort Resources on API ?

Sorting resources on an API may seem complicated, but it is relatively simple. Here are the steps to follow:

  1. Determine the field to sort by: The first step is to decide which field you want to sort by. For instance, if you are sorting products, you may choose to sort by price, product name, or product category.
  2. Choose the sorting order: Once you have identified the field to sort by, you need to decide whether to sort in ascending or descending order. Ascending order means that the data is sorted from the smallest to the largest while descending order means that the data is sorted from the largest to the smallest.
  3. Use the sorting parameter: Most APIs support a sorting parameter that allows users to sort resources. The sorting parameter is usually added to the end of the API URL and specifies the field to sort by and the sorting order. For instance, to sort products by price in ascending order, the URL may look like this:
  4. Test the sorting functionality: Once you have implemented the sorting functionality, you need to test it to ensure that it works correctly. Testing involves trying out different sorting options and verifying that the data is sorted correctly.

Clone the repo from GitHub

If you want to follow along I recommend you clone the API repository from GitHub and make sure you get the code from the “Filtering” branch as it contains the latest code changes up to this article.

GitHub - Osempu/BlogAPI at Filtering
Contribute to Osempu/BlogAPI development by creating an account on GitHub.

Update the QueryPatameters class

Start by adding two new parameters to the QueryParameters class which holds all the parameters used to paginate, filter and now sort the API resources. Add an OrderBy parameter to specify the field to sort by and add another field named OrderAsc which states if the order is ascending if not it will be descending this will be true by default.

public class QueryParameters
    //Code Ommited for brevity

    //Sorting params
    public string OrderBy { get; set; } = string.Empty;
    public bool OrderAsc { get; set; } = true;

Add Sort logic to PostRepositoy Class

Now go into the PostRepository class and add the sorting logic. First, you will check if the OrderBy parameter is not null and if not then proceed to check if the OrderAsc is true to set the order flow or order direction to ascending or descending depending on the case. And lastly call the OrderBy method to perform the sorting operation. But you will get an error because the OrderBy does not accept string as an argument so you have to install a new package to be able to work with dynamic Linq queries.

public async Task<IEnumerable<Post>> GetPostAsync(QueryParameters parameters)
    var allPosts = context.Posts.AsQueryable();

    //Filter by Author
        allPosts = allPosts.Where(x => x.Author == parameters.Author);

    //Sort posts
        string orderFlow = parameters.OrderAsc ? "ascending" : "descending";
        allPosts = allPosts.OrderBy($"{parameters.OrderBy} {orderFlow}");

    //Paginated posts
    var pagedPosts = await allPosts
            .Skip((parameters.PageNumber - 1) * parameters.PageSize)

    return pagedPosts;

Install the System.Linq.Dynamic.Core Nuget package

Proceed to install this Nuget package using the dotnet cli or the Nuget Package manager if you are using Visual Studio.

dotnet add package System.Linq.Dynamic.Core

This package will allow you to perform the sorting operation with the OrderBy method accepting a string as if it were a string query for example “orderby <parameter> ascending”. Now the error should be gone and you can take the API for a test for example you can set the OrderBy parameter to Title and it will order the posts by Title alphabetically or you can go and sort them by CreatedDate and will sort the posts by the date they were created. Also, you can set the OrderAsc parameter to true or false to set the order flow.

Updating the PostResponseDTO class

Now you can sort by CreatedDate but if you tested the API you noted that when the posts were returned they don’t display this property so for that you have to update the PostResponseDTO to display the CreatedDate property so it makes sense when we sort by date. For that, you just have to add the CreatedDate property to the dto and that’s it, now you can see the date when the post was created when getting a single post or a list of posts.

public record PostResponseDTO(int Id, string Author, string Title, string Body, DateTime CreatedDate);

Take your API for a Test

Now you should be able to see the created date displayed and the sorting functionality must be working as expected. Think about what properties you can add tot he Post that you can sort by that can enhance your sorting logic or your API in general.


Sorting resources on an API is an essential aspect of application development. By sorting resources, users can quickly find the information they need, leading to a better user experience. Sorting resources also improves the performance of the application and makes it easier for developers to maintain it. By following the steps outlined in this article, you can easily sort resources on your API in a user-friendly manner.

Thanks for reading!

As always thanks a lot for reading my articles and for following me on my personal Blog, on Twitter, and on my YouTube channel. I don’t think that we can have a Friday API this week but I will work on something great for the next week so keep posted on that. Thanks and keep coding, see you on my next article!