REST API: Path vs. Request Body Parameters
Look at REST API path parameters versus request bodies.
Join the DZone community and get the full member experience.
Join For FreeWhenever we create a REST API, we have to decide which parameter should be present where.
For example, if we are creating a REST API to update student details using PUT (HTTP Method), then the request URI will be {server_host}/students/{student_id}
, and the request body would be:
{
"id": student_id,
"name": "student name",
"school_name": "school name"
}
I have seen that many times, developers get confused about why we need to send the same parameter to multiple places. For instance, in the above example, we are sending the student_id
to the path parameter as well as the request body. It may seem that we are sending repetitive information via the API, but remember that the request body and path parameters have different meanings and should be used for the purpose that they are going to serve.
Below is the explanation of why we cannot remove student_id
from the path parameters and the request body.
Path Parameters
Path parameters are used to identify a resource uniquely. In the {server_host}/students/{student_id}
example, student_id
is identifying a unique student_id
. If we remove student_id from the path parameter, create {server_host}/students
API and use student_id of the request body. Then, on the backend, we can write our logic perfectly fine, but that API will not follow the REST API principle. By looking at the {server_host}/students
API contract, no client would be able to identify that this API is to process the record of only one resource.
Request Body
The request body is used to send and receive data via the REST API. If we are using POST/PUT API, then based on the REST API contract, we should send the whole resource information because these methods work on the whole resource. In the above example, student_id is also part of that resource, so it has to be present in the request body, else the request body would be able to represent the whole resource information.
After removing student_id from the request body, we will have the below request body.
{
"name": "student name",
"school_name": "school name"
}
Does this request body represent the whole resource information? No. So this is a violation of the REST contract.
So, to represent resource state, we need to send student_id in the request body, and to identify the resource uniquely, we need to send the student_id
in path parameter.
Thanks for reading, and let me know your thoughts in the comments.
Opinions expressed by DZone contributors are their own.
Trending
-
Introduction To Git
-
Which Is Better for IoT: Azure RTOS or FreeRTOS?
-
Comparing Cloud Hosting vs. Self Hosting
-
Revolutionizing Algorithmic Trading: The Power of Reinforcement Learning
Comments