Why its recommended to use the GET method to retrieve data in Rest API?
The reason that we don't use POST for everything: using a method with more specific semantics allows general purpose components within the HTTP application to do intelligent things.
Specifically for the case of GET
- Caching
The goal of HTTP caching is significantly improving performance by reusing a prior response message to satisfy a current request. -- RFC 9111
The response to a GET request is cacheable; a cache MAY use it to satisfy subsequent GET and HEAD requests unless otherwise indicated by the Cache-Control header field -- RFC 9110
This means both that a GET request can be served by a cache (rather than passing the request all the way through to the origin server) and that GET responses can be cached for later re-used.
Because POST is potentially unsafe (ie, edits resources), the general purpose components always have to pass the request through to the origin server. POST responses can be cached only in some cases; general purpose components can recognize these specific cases via the metadata provided by the origin server.
- Unlike POST, the semantics of a GET request are safe.
The purpose of distinguishing between safe and unsafe methods is to allow automated retrieval processes (spiders) and cache performance optimization (pre-fetching) to work without fear of causing harm. In addition, it allows a user agent to apply appropriate constraints on the automated use of unsafe methods when processing potentially untrusted content. -- RFC 9110
Most of the designed systems use GET to retrieve since it's idempotent and "theoretically" does not alter data on the server however, nowadays most of the GET requests also create logs on the server or alter caching.
Yes, which is why it is important to understand the distinction between safe semantics and safe implementation
HTTP does not attempt to require the results of a GET to be safe. What it does is require that the semantics of the operation be safe, and therefore it is a fault of the implementation, not the interface
or the user of that interface, if anything happens as a result that
causes loss of property Fielding, 2002
However I guess Its ok to use GET if only retrieval and no sensitive data on URL.
Yes - and notice that's a property of the URI/URL, not the HTTP method. A POST
with sensitive information in the target-uri is no better (or worse) than the equivalent GET
request.
For example; if you are creating an HTML form, and intend to collect sensitive information, then you'll use form.method POST because we don't want the browser to construct a URI with sensitive information in it.
Similarly, a URI template design that uses variable expansion for sensitive information is just asking for problems.
But this should be understood as a URI design problem, not as a necessary feature of HTTP method semantics.