Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use pathParams or QueryParams [duplicate]

Tags:

java

rest

jax-rs

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?

like image 468
Tim Sparg Avatar asked Jun 14 '11 15:06

Tim Sparg


People also ask

What is diff between QueryParam and PathParam?

@QueryParam is used to access key/value pairs in the query string of the URL (the part after the ?). For example in the url http://example.com?q=searchterm , you can use @QueryParam("q") to get the value of q . @PathParam is used to match a part of the URL as a parameter.

When would you use query string parameters vs route parameters?

' in the URL, path parameters come before the question mark sign. Secondly, the query parameters are used to sort/filter resources. On the other hand, path parameters are used to identify a specific resource or resources. You can't omit values in path parameters since they are part of the URL.

What is the difference between Pathvariable and PathParam?

@PathParam: it is used to inject the value of named URI path parameters that were defined in @Path expression. @Pathvariable: This annotation is used to handle template variables in the request URI mapping ,and used them as method parameters.

What is the use of @QueryParam?

The @QueryParam annotation allows you to map a URI query string parameter or url form encoded parameter to your method invocation.


1 Answers

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

like image 155
Gareth Davis Avatar answered Oct 13 '22 18:10

Gareth Davis