Is it valid if I use HTTP method POST for fetching data? - rest

What I know that the HTTP method GET is for fetching/searching data and POST is for create/insert data.
But what if there is a case that I want to search data but the parameters (key-value pairs) are so many or big that there is possibility it will go over the query string limit for the GET method.
In this case, if I use POST for searching data, is it valid in the REST or HTTP specification?

Its perfectly valid in the scenarios where you have lot many number of variable parameters.

Related

Sensitive data into query param GET Api

I have a REST GET API , like
http://localhost:8080/users/{userId}/assignments/{assignmentId}
Since , this is the GET call , so 'assignmentId' will get expose into URL while calling it.
This is the sensitive data for me & i don't want this to be expose publicly.
How can i overcome with this.?
Here are my two cents. Have you considered switching the service to be a POST with a request body that contains the sensitive data? That will solve the problem around not exposing the query param. I have seen services that accept a POST which returns data, but most of them do that to support unbounded inputs (as in retrieving data of multiple IDs).

Should I use GET or POST REST API Method?

I want to retrieve data about a bunch of resources. Let's say an Array of book id and the response is JSON Array of book objects. I want to send the request payload as JSON to the server.
Should I use GET and POST method?
Note:
I don't want to make multiple GET request for each book ID.
POST seems to be confusing as it is supposed to be used only when the request creates a resource or modifies the server state.
I want to retrieve data about a bunch of resources. Let's say an Array of book id and the response is JSON Array of book objects.
If you are thinking about passing the array of book id as the message body of the HTTP Request, then GET is a bad idea.
A payload within a GET request message has no defined semantics; sending a payload body on a GET request might cause some existing implementations to reject the request.
You should use POST instead
POST seems to be confusing as it is supposed to be used only when the request creates a resource or modifies the server state.
That's not quite right. POST can be used for anything -- see GraphQL or SOAP. But what you give up by using POST is the ability of intermediate components to participate in the conversation.
For example, for cases that are effectively read-only, you would like to use a safe method, because that allows pre-caching optimization, and automated retry of lost responses on an unreliable network. POST doesn't have extra semantic constraints, so you lose out.
What HTTP really wants is that you GET using the URI; this can be done in one of two relatively straightforward ways:
POST the ids to the server, to create a new resource (meaning that the server retains for itself a copy of the list of ids), and receive a new resource identifier back in exchange. Then GET using this new identifier any time you want to know the current representation of the results.
Encode the information you need into the URI itself. Most commonly, this is done using the query part of the URI, although that isn't strictly necessary. The downside here is that if the URI encoded representation of the array of ids is very long, you may have trouble with some implementations that enforce arbitrary URI limits.
There aren't always great answers:
The REST interface is designed to be efficient for large-grain hypermedia data transfer, optimizing for the common case of the Web, but resulting in an interface that is not optimal for other forms of architectural interaction.
If I understand correctly, you want to get a list of all of the items in a list, in one pull. This would be possible using GET, as REST returns the JSON it can by default be up to 100 items, and you can get more items if needed by specifying $top.
As far as writing back or to the server, POST would be what your looking for, this to my understanding would need to be one for one.
you are going to use a GET-Request and put your request-data (book-id array) in the data-section of your ajax (or whatever you're going to use) request. See How to pass parameters in GET requests with jQuery

Retrieve only specific properties with REST GET API

I need to define a REST API which is supposed to take the object's unique identifier and return back the content. The content is retrieved from the database and is of JSON type.
So, I have a REST URL like this -
GET /data/{typename}/{objectid}
This would return the entire object content.
However, the content of the object could be large in size and so caller may like to specify only some or few of the properties to be sent as a response.
The natural thought that comes to me is to add a BODY to the GET API where user could specify the list of property names on that object to be retrieved.
But on doing some further research, it appears that a GET API with BODY is not recommended.
The other option that I can think of is to pass the property names in query string -
GET /data/{typename}/{objectid}?property=prop1&property=prop2...
But the list could easily become large.
Any suggestion on how should my API look like? Do I have to use POST?
Technically, using POST will work but is not preferred. If you are reading, use GET. Facebook, for example, has a similar use case where the /me endpoint has many filters, and the call is GET.
The final URL would be,
/me?fields=id,name,about,age_range,devices,currency,education
You can try it yourself from here,
https://developers.facebook.com/tools/explorer/145634995501895/?method=GET&path=me%3Ffields%3Did%2Cname%2Cabout%2Cage_range%2Cdevices%2Ccurrency%2Ceducation&version=v2.8
I recommend reading more about GraphAPI https://developers.facebook.com/docs/graph-api/overview/ and GraphQL https://graphql.org/
I would recommend using POST, because GET has a length limit.
What is the maximum length of a URL in different browsers?
otherwise you could make your query string look like this (for array)
so close :)
GET /data/{typename}/{objectid}?property[]=prop1&property[]=prop2...

Rest POST VS GET if payload is huge

I understand the definition of GET and POST as below.
GET: List the members of the collection, complete with their member URIs for further navigation. For example, list all the cars for sale.
POST: Create a new entry in the collection where the ID is assigned automatically by the collection. The ID created is usually included as part of the data returned by this operation.
MY API searches for some detail in server with huge request payload with JSON Message in that case Which Verb should i use ?
Also can anyone please let me know the length of the characters that can be passed in query string.
The main difference between a GET and POST request is that in the former, the entire request is encoded as part of the URL itself, whereas in the latter, parameters are sent after the header. In addition, in GET request, different browsers will impose different limits on how big the URL can be. Most modern browsers will allow at least 200KB, however Internet Explorer seems to limit the URL size to 2KB.
That being said, if you have any suspicion that you will be passing in a large number of parameters which could exceed the limit imposed on GET requests by the receiving web server, you should switch to POST instead.
Here is a site which surveyed the GET behavior of most modern browsers, and it is worth a read.
Late to the party but for anyone searching for a solution, this might help.
I just came up with 2 different strategies to solve this problem. I'll create proof of concept API and test which one suites me better. Here are the solution I'm currently thinking:
1. X-HTTP-Method-Override:
Basically we would tunnel a GET request using POST/PUT method, with added X-HTTP-Method-Override request header, so that server routes the request to GET call. Simple to implement and does work in one trip.
2. Divide and Rule:
Divide requests into two separate requests. Send a POST/PUT request with all payload, to which server will create necessary response and store it in cache/db along with a key/id to access the data. Then server will respond with either "Location" header or the Key/id through which the stored response can be accessed.
Now send GET request with the key/location given by server on previous POST request. A bit complicated to implement and needs two requests, also requires a separate strategy to clean the cached responses.
If this is going to be a typical situation for your API then a RESTful approach could be to POST query data to a buffer endpoint which returns a URI from which you can GET your results.
Who knows maybe a cache of these will mitigate the need to send "huge" blobs of data about.
Well You Can Use Both To get Results From Server By Passing Some Data To server
In Case Of One Or Two Parameters like Id
Here Only One Parameter Is Used .But 3 to 4 params can Be used This Is How I Used In angularjs
Prefer : Get
Example : $http.get('/getEmployeeDataById?id=22');
In Case It Is Big Json Object
Prefer : Post
Example : var dataObj =
{
name : $scope.name,
age : $scope.age,
headoffice : $scope.headoffice
};
var res = $http.post('/getEmployeesList', dataObj);
And For Size Of Characters That Can Be Passed In Query String Here Is Already Answered
If you're getting data from the server, use GET. If you want to post something, use POST. Payload size is irrelevent. If you want to work with smaller payloads, you could implement pagination.

REST API Design with many input parameters including collections

I need to design and implement a REST API where users need to pass many input parameters. Out of those input parameters few are collection of an integer, few of them are date strings etc. After getting all these parameters I need to return unique id in the response. What method type (PUT, POST or GET) I should use in order to implement this API? How can I pass all these parameters to the API? I don't want users to format input parameter list into XML or JSON and post as a request body.
I appreciate if anybody can help on this topic.
POST is for creating new resources.
PUT is for updating existing resources. A PUT call should be idempotent, i.e. issuing the same request twice will end in no side effects.
To get an overall clue on how RESTful services work, read this article.
And yes, if you want your users to submit a complex set of parameters JSON/XML is the best way to go of course.