Search code examples
c#asp.net-web-api.net-coreasp.net-core-webapihttp-get

Web API HTTPGet for multiple attributes?


We have a Web API written in DotNet Core 3.1.402 (I am new to DotNet Core and WebAPI).

We use SqlKata for Database processing.

We have an Account model that has AccountID, AccountName, AccountNumber, etc.

We would like to get an Account by different attributes, for ex: by AccountID, by AccountName, by AccountNumber.

How can we do that so that we don't need a separate HttpGet for each attribute (so we don't have to repeat the same code for different attributes) ?

This is our HttpGet in the AccountsController to get the account by AccountID

public class AccountsController : ControllerBase
{
    private readonly IAccountRepository _accountRepository;

    [HttpGet("{AccountID}")]
    public Account GetAccount(int AccountID)
    {
        var result = _accountRepository.GetAccount(AccountID);
        return result;
    }

This is the code in the AccountRepository.cs

public Account GetAccount(int accountID)
{
  var result = _db.Query("MyAccountTable").Where("AccountID", accountID).FirstOrDefault<Account>();
  return result;
}

This is the Account class

namespace MyApi.Models
{
   public class Account
   {
       public string AccountID { get; set; }
       public string AccountName { get; set; }
       public string AccountNumber  { get; set; }
       // other attributes
   }
 }

Thank you.


Solution

  • Doing it with GET can be a pain, there are ways to pass on the path/query arrays and complex objects but are ugly, the best you can do is to use POST instead of GET and pass an object with the filters that you want.

    //In the controller...
    [HttpPost]
    public Account GetAccount([FromBody]Filter[] DesiredFilters)
    {
        var result = _accountRepository.GetAccount(DesiredFilters);
        return result;
    }
    
    //Somewhere else, in a shared model...
    public class Filter
    {
        public string PropertyName { get; set; }
        public string Value { get; set; }
    }
    
    //In the repository...
    public Account GetAccount(Filter[] Filters)
    {
        var query = _db.Query("MyAccountTable");
    
        foreach(var filter in Filters)
            query = query.Where(filter.PropertyName, filter.Value);
    
        return query.FirstOrDefault<Account>();
    }
    

    Now you can send a JSON array on the request body with any filters that you want, per example:

    [ 
        { "PropertyName": "AccountID", "Value": "3" }, 
        { "PropertyName": "AccountName", "Value": "Whatever" }
    ]