How do I use WebAPI/Rest correctly when other params are needed

Total Post:70

Points:494
API(s)  Web 
 1234  View(s)
Ratings:
Rate this:

I am new to WebAPI and rest and am trying to do things correctly. By default if I were to access something such as User I would call api/user/5 if I wanted user 5. This would go to my User controller to Get(int num) I think. But I know I will often need other params passed as well. Currently I have Get(JObject data), but that data param is for other parameters. I will need other optional params whether I am sending an ID or wanting a list of everything. How do I go about organizing methods properly with WebAPI? Am I misunderstanding something?

 

To clarify: This question is more about REST than dynamic objects, though they play a part:

 

How do I get a single resource vs a list of resources when I need additional params. I see those concepts as two separate methods, but the additional params complicate it in my mind when routing is involved.

  1. Post:42

    Points:296
    Re: How do I use WebAPI/Rest correctly when other params are needed

    Use attribute routing 

    For example - 

    [Route("customers/{customerId}/orders")]
    public IEnumerable<Order> GetOrdersByCustomer(int customerId) { ... }
    or 
    [Route("customers/{customerId}/orders/{orderId}")]
    public Order GetOrderByCustomer(int customerId, int orderId) { ... }

    if you need to return a list, create a method that returns a list, otherwise return the specific item requested

      Modified On Apr-07-2018 02:26:12 AM
  1. Post:27

    Points:189
    Re: How do I use WebAPI/Rest correctly when other params are needed

    I think you should make a new object for each WebAPI function that will handle the request. You can make the parameters optional with nullable properties. 

    [HttpPost]
    public void SampleFunction(SampleFunctionModel model)
    {
     
    }
    where SampleFunctionModel is:
     
    public class SampleFunctionModel
    {
        public int? Id {get; set; }
     
        public string Name{ get; set; }
    }

      Modified On Apr-07-2018 02:25:46 AM

Answer