Is there a correct way to pass parameters to search?

Asked

Viewed 67 times

6

I am making a Restfull application and it occurred to me the following doubt:

"Am I passing parameters in the correct way for this method?"

The method in question is this:

[HttpGet("{initial}&{final}")]
        public ActionResult<IEnumerable<SalesRecord>> getAllSR(DateTime? initial, DateTime? final)
        {

            return _srService.findByDate(initial, final);
        }

This method gets an initial date and a final date for me to return a Salesrecord list by following my service criteria...

According to GET this will be my URL:

localhost:5001/api/Salesrecord/2018-10-20&2018-10-31

Everything works just fine! However, something seems wrong because it is very simple to separate two dates with only one "&", is there any rule that I should follow as to how to pass parameters in a Restfull API? (for specific search)

1 answer

4


Following the good practice of a HTTP GET you would probably need:

  • Use the noun in the plural, where Salesrecord become Salesrecords
  • Parameterize dates as filters for the Salesrecords feature: /SalesRecords?fromDate=2018-01-01&toDate=2018-12-31

So in your controller you would have:

[HttpGet]
[Route("/SalesRecords")]
public ActionResult<IEnumerable<SalesRecord>> GetSalesRecords(DateTime? fromDate, DateTime? toDate)
{
    return _srService.findByDate(fromDate, toDate);
}

Or "manually formatting" the route:

[HttpGet]
[Route("/SalesRecords?fromDate={fromDate}&toDate={toDate}")]
public ActionResult<IEnumerable<SalesRecord>> GetSalesRecords(DateTime? fromDate, DateTime? toDate)
{
    return _srService.findByDate(fromDate, toDate);
}

  • Another question: What’s the difference between just get and get + route ex: [Httpget("/Salesrecords")] and [Httpget] [Route("Salesrecords")]

  • 1

    It was an error in the hurry. Actually, we use the [Route] annotation to map the route. I made an edit! @Márciosebastião

  • Thank you very much!

  • Taking advantage of the momentum: Even IDS I put only on the route, this is right? It did so [Httpget{id}] [Route("Details/{id}")], now doing so [Httpget] [Route("Details/{id}")]

  • 1

    That’s correct. What you can do is use for example [Httpget{int:id}] to make it clear that the value needs to be an int. On the routes, depending on how your Routing Tables are, some you don’t even need to define with [Route(")]. I suggest this part of the documentation: https://docs.microsoft.com/en-us/aspnet/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api @Márciosebastião

Browser other questions tagged

You are not signed in. Login or sign up in order to post.