Search code examples
javascriptjqueryrestpostget

when is it appropriate to use get vs post request


Background

Let's assume i have some data as follows that i collect based on some survey users fill out in a form:

{
  "brand": "Nike",
  "size": [
    "small",
    "medium"
  ]
}

Now let's say I want to pass this data to some api , in my case i will create api gateway that will forward this request to a aws lambda function. The lambda function request will process this request and look at my rds instance to get all the shirts that are small and medium and return me data as response.

My question:

When I make the ajax call to the api would this be a get request or a post request??

Technically I am not really going to modify the database but rather do a read on the database something like select * from nike where size = 'small' and size = 'medium'

I am confused because i assumed whenever we are trying to "GET"/read some data we do a GET request. However I came across THIS stackoverflow post. where the accepted answer suggests that when we are passing data long like i am above we should rather make a POST request.

So my ajax call would look something like this possibly:

var data =  {
      "brand": "Nike",
      "size": [
        "small",
        "medium"
      ]
    }


$.ajax({
  type: "POST",
  url: "apigatewayendpointblahblah",
  data: data,
  success: success,
  dataType: dataType
});

Solution

  • The Rest Protocol has strict definitions for the methods you should use. when you're fetching data without modifying it, you should use GET request.

    Notice that GET required query params rather than body params, which then can be used as a link for sharing pages.

    Refer to https://restfulapi.net/http-methods/ for more info