Skip to main content

How to define a REST service with pagination support - Part 2

Part 1: http://vunvulearadu.blogspot.ro/2014/08/how-to-define-rest-service-with.html
Part 2: http://vunvulearadu.blogspot.ro/2014/08/how-to-define-rest-service-with_17.html
In this post we will see how we can implement using ApiController, a REST service that expose a list of items using pagination.
In the previous post related to this subject we define the REST API for pagination. We saw how important is for clients to has all the information directly in the message itself. For example the next page URL should be send by the service, not constructs by the clients.
The below example contains the request and response of our REST service.
Request:
GET /api/cars?pageNumber=3&pageSize=20

Response:
{  
   "pageNumber":1,
   "pageSize":20,
   "totalPages":3,
   "totalItemsCount":46,
   "prevPageLink":"",
   "nextPageLink":"/api/car?page=2&pageSize=20",
   "firstPageLink":"/api/car?page=1&pageSize=20",
   "lastPageLink":"/api/car?page=2&pageSize=20",
   "items":[
                    ...
 ]
}
Get items from database
Let’s assume that we are using Entity Framework to fetch data from database. To be able to get only the items that we need for the requested page we will need to use a LINQ expression that contains

  • Skip – to get only the items starting from a specific location
  • Take – take only the items that are needed for the current page

Unfortunately, Skip and Take commands can be used only in combination with OrderBy. Because of this we will need to call and apply an order by before each query. This is needed because this is the only way how EF can guarantee that the items that are returned are the expected one (items from database are not orders).
List<Car> entities = carSet
                                        .OrderBy(x => x.Id)
                                        .Skip((pageNumber - 1) * pageSize)
                                        .Take(pageSize)
                                        .ToList();
On top of this we will need to get the total number of items. For this we will to make another query that retrieves the total available items.
int totalItems = carSet.Count();
Generate response
The response from the repository can we wrapped  in a class that extends List<T> and has a property with all the information related to pagination (page number, size, items count).
public class Page<TItem> : List<TItem>
{
    public Page()
    {
    }

    public Page(IEnumerable<TItem> collection, Paging paging)
        : base(collection)
    {
        Paging = paging;
    }

    public Paging Paging { get; set; }
}
Class that contains all the information related to pagination:
public class Paging
{
    public int PageNumber { get; set; }

    public int PageSize { get; set; }

    public int TotalPages { get; set; }

    public int TotalItemsCount { get; set; }

    public bool HasNext
    {
        get
        {
            return TotalPages > PageNumber;
        }
    }

    public bool HasPrev
    {
        get
        {
            return PageNumber > 1 && PageNumber <= TotalPages;
        }
    }
}
Next we will need to use a dynamic object to generate the response message that contains all the necessary information.
public class PaginationUtility
{
    private const string PageNumberQueryName = "page";
    private const string PageSizeQueryName = "pageSize";
    private const string ErrorMessageForInvalidPage = "This page don't exist.";

    public HttpResponseMessage CreateResponseMessageForPaginaionRequests<TEntity>(Page<TEntity> requestedPage,
        HttpRequestMessage request)
    {
        dynamic bodyMessage = CreateResponseBody(requestedPage, request);

        HttpResponseMessage responseMessage = requestedPage.Count == 0 ||
                                                requestedPage.Paging.PageNumber > requestedPage.Paging.TotalPages
            ? CreateResponseMessageForInvalidPagingRequest(request)
            : CreateResponseMessageForPagingRequest(request);

        responseMessage.Content = new StringContent(JsonConvert.SerializeObject(bodyMessage));

        return responseMessage;
    }

    private static dynamic CreateResponseBody<TEntity>(Page<TEntity> requestedPage, HttpRequestMessage requestMessage)
    {
        Paging currentPage = requestedPage.Paging;
        string uriPath = requestMessage.RequestUri.GetLeftPart(UriPartial.Path);

        string prevPageLink = currentPage.HasPrev
            ? GeneratePaginationNavigationUri(currentPage.PageNumber - 1, currentPage.PageSize, uriPath)
            : string.Empty;

        string nextPageLink = currentPage.HasNext
            ? GeneratePaginationNavigationUri(currentPage.PageNumber + 1, currentPage.PageSize, uriPath)
            : string.Empty;

        string firstPageLink = currentPage.TotalPages == 0
            ? string.Empty
            : GeneratePaginationNavigationUri(1, currentPage.PageSize, uriPath);
        string lastPageLink = currentPage.TotalPages == 0
            ? string.Empty
            : GeneratePaginationNavigationUri(requestedPage.Paging.TotalPages, currentPage.PageSize, uriPath);

        dynamic pagInformation = new
        {
            pageNumber = currentPage.PageNumber,
            pageSize = currentPage.PageSize,
            totalPages = currentPage.TotalPages,
            totalItemsCount = currentPage.TotalItemsCount,
            prevPageLink,
            nextPageLink,
            firstPageLink,
            lastPageLink,
            items = requestedPage.ToList()
        };

        return pagInformation;
    }

    private static HttpResponseMessage CreateResponseMessageForInvalidPagingRequest(HttpRequestMessage request)
    {
        HttpResponseMessage errorResponse = request.CreateErrorResponse(
            HttpStatusCode.NoContent,
            ErrorMessageForInvalidPage);
        return errorResponse;
    }

    private static HttpResponseMessage CreateResponseMessageForPagingRequest(HttpRequestMessage request)
    {
        HttpResponseMessage response = request.CreateResponse(HttpStatusCode.OK);
        return response;
    }

    private static string GeneratePaginationNavigationUri(int page, int pageSize, string uriPath)
    {
        UriBuilder prevUriBuilder = new UriBuilder(uriPath);
        NameValueCollection prevQuery = HttpUtility.ParseQueryString(prevUriBuilder.Query);
        prevQuery.Add(PageNumberQueryName, page.ToString(CultureInfo.InvariantCulture));
        prevQuery.Add(PageSizeQueryName, pageSize.ToString(CultureInfo.InvariantCulture));
        prevUriBuilder.Query = prevQuery.ToString();
        return prevUriBuilder.ToString();
    }
}
ApiController
Our controller is very simple, it only has to call the repository method that gets the items and format the response using the above code.
 [HttpGet]
 public HttpResponseMessage Get(int page, int pageSize)
 {
    ...
 }

Conclusion
We are done. In this post we saw how easy we can expose a REST API with pagination support using EF and ApiController.

Comments

Popular posts from this blog

Windows Docker Containers can make WIN32 API calls, use COM and ASP.NET WebForms

After the last post , I received two interesting questions related to Docker and Windows. People were interested if we do Win32 API calls from a Docker container and if there is support for COM. WIN32 Support To test calls to WIN32 API, let’s try to populate SYSTEM_INFO class. [StructLayout(LayoutKind.Sequential)] public struct SYSTEM_INFO { public uint dwOemId; public uint dwPageSize; public uint lpMinimumApplicationAddress; public uint lpMaximumApplicationAddress; public uint dwActiveProcessorMask; public uint dwNumberOfProcessors; public uint dwProcessorType; public uint dwAllocationGranularity; public uint dwProcessorLevel; public uint dwProcessorRevision; } ... [DllImport("kernel32")] static extern void GetSystemInfo(ref SYSTEM_INFO pSI); ... SYSTEM_INFO pSI = new SYSTEM_INFO(...

How to audit an Azure Cosmos DB

In this post, we will talk about how we can audit an Azure Cosmos DB database. Before jumping into the problem let us define the business requirement: As an Administrator I want to be able to audit all changes that were done to specific collection inside my Azure Cosmos DB. The requirement is simple, but can be a little tricky to implement fully. First of all when you are using Azure Cosmos DB or any other storage solution there are 99% odds that you’ll have more than one system that writes data to it. This means that you have or not have control on the systems that are doing any create/update/delete operations. Solution 1: Diagnostic Logs Cosmos DB allows us activate diagnostics logs and stream the output a storage account for achieving to other systems like Event Hub or Log Analytics. This would allow us to have information related to who, when, what, response code and how the access operation to our Cosmos DB was done. Beside this there is a field that specifies what was th...

Cloud Myths: Cloud is Cheaper (Pill 1 of 5 / Cloud Pills)

Cloud Myths: Cloud is Cheaper (Pill 1 of 5 / Cloud Pills) The idea that moving to the cloud reduces the costs is a common misconception. The cloud infrastructure provides flexibility, scalability, and better CAPEX, but it does not guarantee lower costs without proper optimisation and management of the cloud services and infrastructure. Idle and unused resources, overprovisioning, oversize databases, and unnecessary data transfer can increase running costs. The regional pricing mode, multi-cloud complexity, and cost variety add extra complexity to the cost function. Cloud adoption without a cost governance strategy can result in unexpected expenses. Improper usage, combined with a pay-as-you-go model, can result in a nightmare for business stakeholders who cannot track and manage the monthly costs. Cloud-native services such as AI services, managed databases, and analytics platforms are powerful, provide out-of-the-shelve capabilities, and increase business agility and innovation. H...