Search code examples
c#jsonasp.net-corehttpresponseanonymous-types

Is it good practice to return anonymous type in respond to HTTP GET request?


My Web API where one of GET endpoint return collection of ProductsByCategory.

 public async Task<ActionResult<IEnumerable<ProductsByCategory>>> GetProductsByCategories()
 {
        var productsByCategories = await northwindContext.Categories.Select(category => new ProductsByCategory
        {
            CategoryName = category.CategoryName,
            ProductCount = category.Products.Count
        }
        ).ToListAsync();

        return productsByCategories;
 }

But I know that JSON and even XML don`t need in name of the type. They just need in name of the property and its value. So I have another way how to implement this method(using anonymous types):

    public async Task<ActionResult<IEnumerable>> GetProductsByCategories()
    {
        var productsByCategories = await northwindContext.Categories.Select(category => new 
        {
            CategoryName = category.CategoryName,
            ProductCount = category.Products.Count
        }
        ).ToListAsync();

        return productsByCategories;
    }

I liked second approach because I don't need in writing code of such types like ProductsByCategory and seems to me more logical since JSON(XML) don't need in type's name I don't need to create not anonymous type. But this is all my thoughts and I am pretty new in field of ASP .NET Core and it is possible that I miss some parts and my guesses are wrong. So is it good practise to pass collection of anonymous types as respond to HTTP GET request or is it better to specify what type of items is collection keeps?


Solution

  • You right, you will have the same resulting serialized object (xml, json), and you can use anonymous type. But you should keep in mind:

    1. When your explicitly define resulting class, your code will be cleaner
    2. For explicitly defined resulting class your may define some validation rules using attributes for serializer
    3. If you use documentation tools, for example swagger, you also may use attributes to provide additional documentation.

    Api should not be ambiguous. Everything depends on your preferences. If you want use anonymous type, you may.