When to use pathParams or QueryParams [duplicate]

早过忘川 提交于 2019-12-20 08:40:35

问题


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:


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




回答2:


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.



来源:https://stackoverflow.com/questions/6345769/when-to-use-pathparams-or-queryparams

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!