33

Is there a rule of thumb as to when one should use path parameters for a URL versus when you should use query parameters?

Say I've got a table Invoice with the fields company(PK),InvoiceNo(PK), Invoiceline, invoiceValue, noOfLines, salesPerson

My current thinking is that your URL should be along the lines of

/Invoice/

Which would display all invoices

/Invoice/{company}

Which would display all invoices for the company.

/Invoice/{company}/{InvoiceNo}

Displays that specific invoice and

/Invoice/{company}/{InvoiceNo}?invoiceLineNo=23

displays only line 23.

The way I'm thinking is that Primary key fields should be part of the path and any other fields that you would filter on are part of the query parameter.

Does this sound like a reasonable way of distinguishing between the two?

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
Tim Sparg
  • 3,294
  • 2
  • 27
  • 40

2 Answers2

50

My personal rule of thumb that the PathParam leads upto the entity type that you are requesting.

/Invoices             // all invoices
/Invoices?after=2011  // a filter on all invoices

/Invoices/52          // by 52
/Invoices/52/Items    // all items on invoice 52
/Invoices/52/Items/1  // Item 1 from invoice 52

/Companies/{company}/Invoices?sort=Date
/Companies/{company}/Invoices/{invoiceNo} // assuming that the invoice only unq by company?

To quote Mr Rowe: Path parameters for grouping data, query parameters for filtering

Community
  • 1
  • 1
Gareth Davis
  • 27,701
  • 12
  • 73
  • 106
  • @Gareth Is there a framework that you use that automagically wires entities to URLs? for example sort=Date would be really nice to have, but unless I had a specific need I wouldn't think to include it. – Tim Sparg Jun 15 '11 at 08:15
  • Not that I know off. I've actually written a semi automagic version of that in one of my apps, it applied a `PaginationRequest` against a hibernate/lucence query, but like all these things pulling it out and opensourcing it is quite a bit of work – Gareth Davis Jun 15 '11 at 08:21
  • @Gareth Is that lucence as in lucene the nuisance? ;-) – Gary Jun 16 '11 at 06:42
  • @GarethDavis What about when making alterations to data? – Tony Sep 24 '14 at 18:18
  • @Tony pretty much the same applies.. so POST /Invoices/52/Items << add a new item to invoice 52 PUT /Invoices/52/Items/2 << update item 2 on invoice 52 – Gareth Davis Sep 25 '14 at 08:02
  • https://developer.yahoo.com/social/rest_api_guide/partial-resources.html#paging-collection – traditional Oct 05 '14 at 16:59
7

Just to add to Gareth's answer, optional parameters are also easier to put as query params. Usually it is the constraints of your server framework that dictate which is the best option. It's not really wise to try and infer too much semantic significance to whether a parameter is a query param or a path param. Remember, URIs are opaque to the client.

Darrel Miller
  • 139,164
  • 32
  • 194
  • 243