javaspringrestspring-bootrestful-architecture

REST API, when to use @PathParam, @QueryParam, @RequestBody, and/or @RequestHeader


I have been trying to find an answer if there is some sort of standard in regards to when/when not to use the above methods of passing information to a REST call.

I have been looking everywhere but every post only talks about the difference between 2 of the listed methods, or 3, not all 4.


Solution

  • 1. @PathParam

    PathParam is generally used to get to a Resource using it's id. Eg. /employees/{emp_id}

    Usually it's a HTTP response code 404 if you don't find an Resource by it's id as path param.

    2. @QueryParam

    QueryParam is generally used to get to an entity using any other field than it's id. Think of "search" or "filter" rather than using "id" to reach the entity. In this case, you will have to expect an array of entities as the response unlike the single entity that you will get as the response for sending id as pathParam

    Ex. /employees?firstname=joe

    Note: QueryParam can be used for other operations too, such as sort. Eg. /departments/123/employees?sort_by=salary

    Usually it's an http response code 200 with an empty array as the response body, if you don't find any entities by the search parameter(s) or filter parameter(s).

    3. @RequestBody

    Usually it's a POST, PUT or PATCH http verb with which we will send the requestbody.

    Why it's a bad idea to send requestbody with http GET

    Why it's a bad idea to send requestbody with http DELETE

    Following are the situations where we use RequestBody

    A. State Mutation

    To achieve state mutation, usually json/xml representation of entity's desired state will be sent as requestBody with POST/PUT/PATCH verb. Rest principles doesn't say anything about json or xml, it can be anything; it can be compressed binary formats such as protobuf, avro, cap'n'proto, flatbuffers etc or even plain text too.

    B. READ operations (These are examples where READ doesn't equate to HTTP GET)

    4. @RequestHeader

    Generally used for sending metadata; Not the actual entity body (data). Eg. request-correlation-id, authheader, security tokens etc

    5. @Matrixparam, @CookieParam etc

    There are other not-so popular HTTP verbs like @Matrixparam and @CookieParam are out there in the JAX-RS spec. This is the Jersey documentation (Keep in mind that Jersey is reference implementation of JAX-RS. You may not find equivalent thing in Spring)

    Other interesting & related reads

    When to use @QueryParam vs @PathParam

    What is the difference between @PathParam and @QueryParam

    HTTP POST with URL query parameters -- good idea or not?

    How do I POST JSON data with cURL?