Using POST method instead of GET in a rest API - java

Is there a specific scenario where we use a POST instead of GET, to implement the functionality of get operation ?

GET is supposed to get :) and POST is used to mainly add something new or sometimes often used for updates as well (although PUT is recommended in such scenarios). There is no specific scenario where we use a POST instead of a GET, if we require this, that means we are probably doing it wrong, although nothing stops you doing this but this is bad design and you should take a step back and plan your API carefully.
There are 2 important cases for a POST i.e. POST is more secure than a GET and POST can send large amount of data but even with this I won't recommend why one will use POST to simulate a GET behaviour.

Lets understand usage of get and post :
What is GET Method?
It appends form-data to the URL in name/ value pairs. The length of the URL is limited by 2048 characters. This method must not be used if you have a password or some sensitive information to be sent to the server. It is used for submitting the form where the user can bookmark the result. It is better for data that is not secure. It cannot be used for sending binary data like images or word documents. It also provides $_GET associative array to access all the sent information using the GET method.
What is POST Method?
It appends form-data to the body of the HTTP request in such a way that data is not shown in the URL. This method does not have any restrictions on data size to be sent. Submissions by form with POST cannot be bookmarked. This method can be used to send ASCII as well as binary data like image and word documents. Data sent by the POST method goes through HTTP header so security depends on the HTTP protocol. You have to know that your information is secure by using secure HTTP. This method is a little safer than GET because the parameters are not stored in browser history or in web server logs. It also provides $_POST associative array to access all the sent information using the POST method.
Source: https://www.edureka.co/blog/get-and-post-method/
So both the methods have their specific usage.

POST method is used to send data to a server to create or update a resource.
GET method is used to request data from a specified resource.
If you want to fetch some data you can use the GET method. But if you want to update an existing resource or create any new resource you should use POST. GET will not help you to create/update resources. So exposing the api should be specific to your needs.
UPDATE
So your main question is in what scenario we can use POST to implement the functionality of GET.
To answer that, as you understand what GET and POST does, so with GET request you will only fetch the resource. But with POST request you are creating or updating the resource and also can send the response body containing the form data in the same request response scenario. So suppose you are creating a new resource and the same resource you want to see, instead of making a POST call first and making a GET call again to fetch the same resource will cost extra overhead. You can skip the GET call and see your desired response from the POST response itself. This is the scenario you can use POST instead of making an extra GET call.

Related

Use cases of #PatchMapping

There is a RequestMethod named PATCH.
To use this method, we can define #PatchMapping for a rest endpoint.
As per my understanding, it sounds like partially updating the DB object.
Generally, we use POST or PUT calls to perform save or update. So, still not clear what are exact use cases of PatchMapping and why can't I just use PUT instead of PATCH?
still not clear what are exact use cases of PatchMapping and why can't I just use PUT instead of PATCH?
PUT (defined by RFC 7231) and PATCH (defined by RFC 5789) are two different methods used for a similar purpose: to request that the server make its representation of a resource match the representation on the client.
Imagine, if you would, trying to update a web page provided by a server. The client first obtains a recent copy of the server's representation:
GET /foo
and then, using the client's favorite local HTML editor, makes changes to this private copy. When the client has finished making the changes, we want to send those changes back to the server to be used.
The straight forward way to do this in HTTP is to simply send the entire updated representation back to the server:
PUT /foo
<html>....</html>
When the representation is very large (compared with the HTTP headers), and the edits are very small (compared to the document), then PUT becomes a somewhat "expensive" way to achieve what ought to be a small thing.
To that end, we might also support PATCH, so that instead of sending the entire document, we just send a representation of the changes we made: a patch document.
When the server receives our patch, it loads its own copy of the document, applies the changes described by the patch document, and saves the result.
Thus: the overall use case is the same: remote authoring. You load a representation of a resource into your HTTP aware document editor, make a few changes, and hit "save", and your editor knows what to do to communicate your edits back to the server.

Return an integer from server to client in response to a REST call

I have a situation where the client (.js) initiates a REST request and it is processed on the server side (.java). After processing, I would like to return a count to the client, which will be shown in a popup box if it is positive. How can such a construction be done? The idea I had was to set a named parameter on the HttpServletResponse object, but even this object is no where in scope in the .js code. Any ideas? I should also clarify that the primary purpose of the REST call is to download a file to the client. Thanks!
Do you want to send two things to your client - sending a file and also additional data? You haven't mentioned what framework (if any) you are using in backend to do this. You can use response header.
From your question, it seems like you don't have a good general-purpose way of responding to client requests on your server. I'd recommend you decide on a data format you'd like to use for all calls (e.g., JSON, XML, etc.) and stick with that across the board.
Once you've made that decision, you can encode your integer using whatever makes sense in your chosen format. For example, in JSON you might return: {"count":6}.

Send a bunch of values from jsp to java code

I have a form on my jsp with fields - Name, IP, username, token.
It is mapped to a table with same column names. I have created a Bean class too.
Now, I am not sure what is an ideal way to send all the parameters from jsp to the java code.
I know few options like -
Create input with type hidden and then set its value in the jsp.
<input type="hidden" id="name" name="name"/>
and then retrieve its value in the code using request.getParameter("name")
Somehow I dont feel this is an ideal way.
Create a JSON with all the values of the input boxes and set the json file as one input and read it on the java code using org.json;
Which one of the two is the better way to do it? Is there any simpler, effective and much better way?
Everything which is built using HTTP methods must send values to the server in one of three places:
Parameters in the url itself (GET requests)
Content in the body of the request (POST requests)
Key-value pairs in the header of the request (HTTP method agnostic)
Any mechanism you use to send a value back to the server (excluding web sockets), no matter what the framework, will use one of these mechanisms underneath.
That being said, use whatever best meets the requirements of your application:
Form-based, GET requests:
are simple to understand
don't require much overhead either on the front-end or back-end
are easy to test (just access the url using the appropriate query string)
Form-based, POST requests:
are also simple to understand
also don't require much overhead either on the front-end or back-end
are not as easy to test (you can't just access the url using the appropriate query string)
Ajax-y, JSON body, POST requests:
are the new hotness
require a bit more front-end work (creating the request in JS and sending it)
don't require the browser to make a full-page request/response

How to add a flag to existing POST api

I have a REST api built for creating orders. The behavior is such that the person who creates an order received an email back saying "You created an order XXX". This email is triggered all the time.
The api appears like this
http://api.mytestevnt.com/ordering/orders - POST with request body as the order entity json.
Now i want to give a feature to the api caller to indicate if the email notification is necessary or not. What's the best way to do this?
I think it depends on whether email notification is data or metadata. If it's part of the order, then definitely add it to the request body. If it's metadata, you have two choices. If you think there will be lots of metadata, you can either edit the order to have a metadata section or you can POST the metadata separately. If there will only be a limited amount of metadata, I would suggest using a query parameter.
You should avoid using a header unless you control the entire path from the client to the server, because proxies or load balancers are allowed to strip non-standard headers.
Include in the POST body a send_email=1 or send_email=0 param. You'll extract that, and see what the user wants to do.
Search "how to get POST variables in JAVA".
Accessing post variables using Java Servlets
You can do like this:
Add a new Java attribute(like boolean emailEnabled) in your Java Request Object for your REST service.
Client side which invokes your REST service need to provide that parameter you added in your server side, you can set a default value for that too.

Programmatically sending mule message (formerly: Accessing mule http endpoint from java)

Scroll towards the end for the solution to the topic's problem. The original question was asking for a somewhat different thing.
As a part of a larger process, I need to fetch and link two related sets of data together. The way that the data is retrieved(dynamics crm, n:n relationships..) forces us retrieve the second set of the data again so that it will have all the necessary information. During a part of larger transformation of this data, I would like to access the http endpoint that is used to fetch the data from the crm, retrieve the second set of data and process it. I can get the endpoint through DefaultEndPointFactory like so:
DefaultEndpointFactory def = new DefaultEndpointFactory();
def.getInboundEndpoint("uri").getConnector;
But there is no method to actually send the mulemessage.
Solved:
The problem is that you can not set inbound properties on the MuleMessage, and the flow is depending on some of those to function(path, query params etc).
It seems you are able to inbound scoped properties with this:
m.setProperty("test", (Object)"test", PropertyScope.INBOUND);
Is there a way to make this approach work, or an alternative way to access the flow? I tried using mulecontext to get the flow:
muleContext.getRegistry().lookupFlowConstruct("myflow");
But it did not contain anything that looked useful.
Solution:
As David Dossot suggested in a comment of his answer, I was able to solve this with muleClients request method.
muleContext.getClient().request(url, timeout);
Then constructing the url as usual with GET parameters etc.
I'm not 100% sure about what you're trying to achieve but anyway, the correct way of using Mule transports from Java code is to use the MuleClient, which you can access with muleContext.getClient().
For example, the send method allow you to pass a properties map that are automatically added to the inbound scope. Behind the scene, Mule takes care of creating the endpoint needed for the operation.
Regarding the flow: what are you trying to do with it? Invoke it?

Categories

Resources