I am just getting started with REST API and I have a few question. I am not sure exactly when it's best to use query parameters or path parameters or to send data in the body?
Right now I am designing a social media platform, and for example I don't know if when a user adds a comment, how should he use it? Is adding it in the request body the best option?
Please, also explain in general, not only for this example. Thank you!
CodePudding user response:
I am not sure exactly when it's best to use query parameters or path parameters or to send data in the body?
query parameters and path parameters are part of the resource identifier; these tell the server which resource we are talking about.
The information that describes how you want the server to change its resources belongs in the request body.
For example, when I submit this answer to stack overflow, the text I'm currently typing belongs in the HTTP request body.
The real difference between query parameters and path parameters is pretty small: with path parameters, other resources with identifiers in the same hierarchy can be described using relative references; with query parameters, you support the creation of general purpose HTML forms that can be used to compute resource identifiers.
But that's purely a mechanical concern. The machines don't care very much, so you can choose any spelling conventions that make life easier for some humans you care about.
CodePudding user response:
First of all you should decide which method to use:
GET - retrieve data
PUT - update data
POST - create data
DELETE - remove data
For your example with comment I would use POST or PUT depending on your architecture. Normally both of them are used with the "body".
Query parameters are mostly used with GET for filtering etc. when you are obtaining some data.