Skip to main content

USE Query action to return a list of a resource

Returning an array of items from a query endpoint is a common practice in web development when building APIs. This approach allows clients to request a collection of resources that meet certain criteria, such as all products in a specific category, or all users that have a certain role.

By returning an array of items from a query endpoint, developers can provide a flexible and powerful API that can meet the diverse needs of their clients. This approach also makes it easy to paginate the results, allowing clients to request specific subsets of the data, rather than returning all items in a single request.

While code block below seems very simple, there are a few constraints needs to be followed while developing a query endpoint. Let's follow what's been done in this example from a UsersController:

  • Name your method as QueryUsers, not QueryUser, not singular
  • Return an array of items and name response type matching to method name as in QueryUsersResponse
  • Get requests parameters from query string and name your complex request type after that method as in QueryUsersRequest
  • Define an empty route as in [HttpGet("")]
  • Place appropriate ProducesResponseType attributes for each return type
  • Never return 404 from a query endpoint. If no data was found, return an empty array
  • Always return HTTP 200 response code unless there was an error
[HttpGet("")]
[ProducesResponseType(StatusCodes.Status200OK, Type = typeof(List<QueryUsersResponse>))]
public async Task<IActionResult> QueryUsers([FromQuery] QueryUsersRequest request)
{
List<QueryUsersResponse> results = new List<QueryUsersResponse>();
return Ok();
}

Never implement custom methods other than described 6 actions (Query, Get, Create, Update, Patch, Delete).