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?

1

2 Answers 2

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

6
  • @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, 2011 at 8: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 Jun 15, 2011 at 8:21
  • @Gareth Is that lucence as in lucene the nuisance? ;-)
    – Gary
    Jun 16, 2011 at 6:42
  • @GarethDavis What about when making alterations to data?
    – Tony
    Sep 24, 2014 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 Sep 25, 2014 at 8:02
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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.