Search code examples
restweb-servicespostgethttp-method

Different response for same API but different method (GET and POST)


I think this is a classic and typical question but I didn't find its answer.

In my knowledge, the POST method is used to send data to the server with request parameter in message body to make it secure. And GET method is to retrieve data with parameters in the URL. But what I didn't understand is how the same api may have different behavior by just changing the method.

Here is an example. I use SoapUI 5.5.0, this is the link of the api: https://reqres.in/api/users/1

when I use GET method I get this:

{
  "data": {
    "id": 1,
    "email": "george.bluth@reqres.in",
    "first_name": "George",
    "last_name": "Bluth",
    "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg"
  }
}

and by changing only the method to POST, I get this:

{
   "id": "244",
   "createdAt": "2020-02-27T14:30:32.100Z"
}

(the id and date changes each time) as described in this link https://reqres.in/ that it is creating an instance and we can add parameters..

BUT, can any one explain how is it technically possible to have different behavior with different methods on the same URL.


Solution

  • In my knowledge, the POST method is used to send data to the server with request parameter in message body to make it secure. And GET method is to retrieve data with parameters in the URL.

    That's probably getting in your way.

    HTTP Requests are messages; each message starts with a request-line

    method SP request-target SP HTTP-version CRLF
    

    The request-target identifies the target resource upon which to apply the request

    The method token indicates the request method to be performed on the target resource.

    You can think of it being like a function call

    GET(target-resource)
    POST(target-resource, message-body)
    

    Or equivalently you can think of the resources as objects that share an understanding of message semantics

    target-resource.GET()
    target-resource.POST(message-body)
    

    But what I didn't understand is how the same api may have different behavior by just changing the method.

    The same way that an api can exhibit different behavior by just changing the request-target.

    In HTTP, the request-line is literally human readable text that the server will parse. Having parsed the request-line, the server program can then branch to whatever code it wants to use to do the work, based on the values it found in the message.

    In many frameworks (Spring, Rails) the branching logic is provided by the framework code; your bespoke handlers only need to be correctly registered and the framework ensures that each request is forwarded to the correct handler.