Sending two http resonses to client for a single httprequest - scala

Is there any way to send out two httpresponses for a single httprequest in play framework.
As as per the RFC of http we can send out two messages for a single request although as I am really novice in Play framework, can this be done.
If not what might be the best approach to solve this scenario

Little note: This solution does not use chucnked, and use the xmlHttp request instead. And also, there is no magic: two requests and two responses. So if you have a constraint on the front-end framework; this might not be the best answer.
You also commented this:
not at once , need to send ok response as an handshake then followed with the actual response which is calculated after extensive mathematical operations
So, if you don't have any constraints on your front-end framework; I would simply use the advantage of Javascript to send the second request, in the background, and get the second response back. Here how I would do it:
Update my views file to take a parameter, handShake of type Boolean. So when to user goes the page for the first time, the controller method response is false. After the first hand shake, the controller method, sends true with Ok response to the user. Only then when it is true the app itself sends another request, as an xmlhttp request via the javascript code, to the controller, and then the corresponding controller method, calculates what it needs to calculate and sends the response back.
This way you send two requests, and get back two responses, but you don't reload the whole page for the second request.

Related

Recommended or not: Sending a JSON body via POST HTTP Request without modification

Is it recommended to send a JSON body via a POST HTTP Request which doesn't modify anything?
Based on the link below, a Get request is not recommended to have a body. Thus, the other way is the one above.
HTTP GET with request body
Example:
Get the list of users, or anything for that matter based on parameters.
Http GET example.com/users
Body
{
name:"John",
age:1,
... long list of parameters
}
Is it recommended to send a JSON body via a POST HTTP Request which doesn't modify anything?
The rule is that POST is the default; it should be used unless there is something better.
For a request with "effectively read only" semantics, you want to use GET instead of POST... if it works. The challenge can be those cases where the request-target (aka: the URI) gets long enough that you start running into 414 URI Too Long responses. If your identifier is long enough that general purpose components refuse to pass the request along, then it is not something better, and you fall back to POST.
An origin server SHOULD NOT rely on private agreements to receive content, since participants in HTTP communication are often unaware of intermediaries along the request chain. (HTTP Semantics, 9.3.1)
In other words, introducing a private agreement to include content in a GET request trades away inter-op, which - if you want "web scale" - is not a winning trade. So GET-with-a-body is not better, and you fall back to POST.
The HTTP working group has been working on semantics for a new "effectively-read-only-with-a-body" method token, which could prove to be an alternative for requests where you need to include a bunch of information in the body because it is too long to encode it into the URI. But we don't have a standard for that today, which means that it is not something better, and you fall back to POST.

GET or POST for stateless RESTFUL API

I'm writing a stateless API. You send it a document, it processes the document, and then returns the processed document. I'm struggling to understand how the RESTFUL rules apply. I'm not retrieving data, creating data or updating data on the server. There is no data on the server. What do I need to use in this case as the http method and why?
Good news - you are right that it is confusing.
Nothing on the server changes in response to the request. That suggests that the request is safe. So GET is the natural choice here... BUT -- GET doesn't support message payloads
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.
HEAD, the other ubiquitous safe method, has the same problem (and is unsuitable when you want to return a document in any case).
The straight forward thing to do at this point is just use POST. It's important to realize that POST doesn't promise that a request is unsafe, only that it doesn't promise that it is safe -- generic components won't know that the request is safe, and won't be able to take advantage of that.
Another possibility is to look through the method registry, to see if somebody has already specified a method that has the semantics that you want. Candidates include SEARCH and REPORT, from the WebDAV specifications. My read of those specifications is that they don't actually have the right semantics for your case.
A Lot of ways to do what you want. But here is a small guideline.
I would create an endpoint that receives the document:
/receive_document
with a 'POST' method. Since you are 'sending' your document to the server
I would create an endpoint that serves up the processed document:
/processed_document
with a 'GET' method. Since you want to retrieve / see your document from the server?
The problem that you are trying to solve is mainly related to the document size, and processing time before returning the response.
Theorically, in order to use a restful approach, you have an endpoint, like yourhost.com/api/document-manager (it can be a php script, or whatever you are using as backend).
OK, so instead of naming the endpoint differently for each operation type, you just change the HTTP method, I'll try to make an example:
POST: used to upload the document, returns 200 OK when the upload is completed.
GET: returns the processed document, you can also return a different HTTP code, in case the document is not ready or even different if the document hasn't been uploaded. 204 no content or 412 precondition failed can be good candidates in case of unavailable document. I'm not sure about the 412, seems like it's returned when you pass a header in the request, that tells the server which resource to return. In your case, I think that the user processes one document at time. But to make a more solid api, maybe you can return an ID token to the user, into the POST response, then forward that token to the GET request, so the server will be able to know exactly which file the user is requesting.
PUT: this method should be used when updating a resource that has been already created with POST
DELETE: removes a resource, then return 204 or 404
OPTIONS: the response contains the allowed methods on this endpoint. You can use it to know for example which privileges has the currently logged user on a resource.
HEAD: is the same as a GET call, but it shouldn't return the response body. This is another good candidate for you to know when the document has been processed. You can upload with POST, then when the upload is done, start some kind of polling to the same endpoint with the HEAD method, finally when it will return "found", the polling will stop, and make the final GET call, which will start the download of the processed document.
HTTP methods are a neat way of managing HTTP communications, if used properly are the way to go, and easily understandable by other developers. And not to forget, you don't have to invent lots of different names for your endpoints, one is enough.
Hope that this helped you a little... But there are loads of guides on the net.
Bye!

HTTP GET request with body for RESTful API [duplicate]

This question already has answers here:
HTTP GET with request body
(23 answers)
Closed 2 years ago.
I've been looking at how to implement the following:
I am developing a RESTful Web API (using .Net Core 2.2). I need to create an endpoint where the consuming client can send some text to the API, the API replaces some tokens in this text, and returns the text back to the consuming client.
I thought that the client should simply do a GET request, with the text in the body. The reply would then be the new text after the token replacements. However, from my research, it appears one should not stick anything with semantics in the body of a GET request. I'm not sure if arbitrary text with certain tokens that need to be replaced by the API qualifies as semantic? I've also seen it stated at "you should not be able to use the body of a GET request to alter the response". I guess I'm in trouble there, as depending what goes into he body, will affect the response.
So then, I've been struggling to figure out what is the correct way to do this. If anyone has an pointers I'd greatly appreciate it.
Thank you.
I thought that the client should simply do a GET request, with the text in the body. The reply would then be the new text after the token replacements. However, from my research, it appears one should not stick anything with semantics in the body of a GET request.
Right - RFC 7231
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.
In basic HTTP, you've got choices. One is to include a representation of your document in the URI itself
/?your_document_as_a_query_string
/your/document/as/path/segments
For short documents, that approach can be fine; but implementations are not required to support infinitely long identifiers, so you may discover that intermediate components reject your request, or crop the URI in transit.
A safe mechanism for achieving your goal is to use POST, rather than GET. POST supports a message body, so you can send the blank form to the server, and receive back the edited version in the response.
POST is the wildcard method of HTTP, it can mean anything. In the spec, the body of the response includes "a representation of the status of, or results obtained from, the action".
You might also consider that the response duplicates a lot of the content of the body of the request, and consider instead the possibilities of fetching a map of your template values from the server, and then applying the template on the client.

Requesting RESTful GET with meaningful Body? Standards not clear

We found ourselves in a dead end when trying to follow standards as we need to build a request that should be a GET and should have a meaning Body.
The request just wants to retrieve some data, no modification inside the database, just getting some data. But at the same time we need to send an array of ids for the objects we want to retrieve, and no, these objects can't be indexed in any way so we really need to send the list of ids or alternatively make 100 requests to the server to get them one by one. That's not gonna happen.
We could also add the list to the URL, but we can't be sure the URL won't end up being too long if the list of ids were to be too big. So to ensure the system doesn't fail we want to use the Body.
I read that a GET can have a Body, but only if it isn't meaningful:
HTTP GET with request body
Yes. In other words, any HTTP request message is allowed to contain a message body, and thus must parse messages with that in
mind. Server semantics for GET, however, are restricted such that a
body, if any, has no semantic meaning to the request. The requirements
on parsing are separate from the requirements on method semantics.
So, yes, you can send a body with GET, and no, it is never useful to do so.
This is part of the layered design of HTTP/1.1 that will become clear again once the spec is partitioned (work in progress).
....Roy
But our Body IS meaningful, which takes us to have to decide between unfollowing HTTP standards or unfollowing REST standards.
Is there any alternative to that? (It's not that this blocks us but I would like to know the answer).
Thank you very much.
you should consider changing your request to POST method.
As I understand it, there are three potential issues with a GET with request body: (link to blog)
Not all servers will support this.
Not all tools will support this (Swagger, POSTMAN added support this year: https://github.com/postmanlabs/postman-app-support/issues/131)
There is not yet a consensus on GET with request body. (For example, is Dropbox still using a POST)
so you'll have problems process the body with GET

HTTP response code for stale pagination

I have a web service that runs a SQL query, sorted by one of several columns, and returns a single requested page (as in skip M limit N). The UI in front of it follows a 'load more' pattern, accumulating all loaded pages of results in one view.
The problem is new and deleted records, which can happen at any time, causing the result of a 'load more' to be wrongly aligned, and depending on the sort being used, even obscuring new records that should be shown. In addition to an automatic refresh on a timer in the frontend, I'm going to add a timestamp field to the RESTful request and response format to allow the webapp to detect that the view should be completely reloaded on a 'load more' call.
My question is, what HTTP status code is a best fit for this signal? In reviewing the codes I don't see an exact fit. I thought of using 302 Found with a link to 'page 1', but I wonder if that might cause unwanted caching of the redirect. I also thought of 400 Bad Request, but there's nothing actually wrong with the request, it's just the data needs to be reloaded.
Pages are served from a POST /path call where the requested page is provided in a JSON body.
I'm not a complete purist, so anything that would make it work without caching or other side effects is acceptable, but I would like to adhere to REST principles as much as possible.
anything that would make it work without caching or other side effects is acceptable
Responses to POST requests are not cacheable unless you explicitly mark them as such. So you can use any combination of status code, response headers and response entity to communicate the “please reload” message to the client.
You can use conditional requests. Include your client’s timestamp in the If-Unmodified-Since header. Respond with 412 Precondition Failed if client is stale. The client will have to know how to reload.
You can try 307 Temporary Redirect, but only if you encode pagination in /path, because upon receiving 307, (I’m assuming you’re doing AJAX here) XMLHttpRequest will transparently re-submit the same POST request to the new Location (at least this is what my Chromium does). Your actual page JSON will have to include metainformation on the range it covers, so that the client knows it has to replace the rows, not append them.