Is it possible to return HTTP code 200, but give a "better" url without using 3xx? - http

Consider StackOverflow, where each question has a unique ID, but URLs are often overridden to include a stub in the URL. For readability and other reasons the stub helps users know they are at the right place.
I have a site that returns 200 when calling a URL like:
http://stackoverflow.com/questions/28057406/
But want the URL to update to:
http://stackoverflow.com/questions/28057406/is-it-possible-to-return-http-code-200-but-give-a-better-url-without-using-3x
The first call is technically valid and the code can retrieve the object and render it perfectly fine, but I'd like to update the URL to use the stubified one.
I'd prefer to do this without a redirect as just getting the ID causes a database call to get the object. Which would mean with a redirect the process would be:
Call http://stackoverflow.com/questions/28057406/
Retrieve item 25257999 from the database to get the name to make the stub
Redirect to http://stackoverflow.com/questions/28057406/is-it-possible-to-return-http-code-200-but-give-a-better-url-without-using-3x
New HTTP Call, so retrieve item 25257999 from the database to render the final page.
If possible I'd like to not use Javascript either.
So, is it possible to return Location as part of a HTTP header with a status code of 200 and the actual page, or am I stuck using 3xx calls or Javascript?

If you are just doing HTTP, you can either choose to redirect, or not choose to redirect... You can also (with Content-Location) tell the client that the canonical address is actually somewhere else... but no browser will respond to that.
To avoid the database-call, you could of course just cache the result.
If you are in a browser however, you can dynamically update the current address without forcing a refresh, with window.history.pushState.
For more information about that call, see this other SO answer:
Modify the URL without reloading the page

Related

How to eliminate false success messages when implementing post-redirect-get pattern?

When implementing the post-redirect-get pattern in a web application, it is common for the final step in your server code to look something like this (pseudocode):
if (postSuccessful)
{
redirect("/some-page?success=true")
}
That is, the redirect URL has some kind of success parameter in the query string so that you know when to display a nice looking "Your form has been submitted!" message on your page. The problem with this is that the success=true persists in the query string when it's only needed to initialize the page. If the user refreshes the page or bookmarks it, they will receive a false success message even though no additional POST has taken place.
Is there an elegant solution to this that doesn't involve using JavaScript to eliminate success=true from both the query string and the browser history? This solution works, but definitely adds complexity to a page's load process.
You can use server side technology to implement this feature, without any JavaScript. The stes are listed below:
When post is successful, redirect to /some-page with current timestamp information:
if (postSuccessful)
{
redirect("/some-page?success=true&timestamp=1559859090747")
}
When server receives GET /some-page?success=true&timestamp=1559859090747 request, compare the timestamp parameter with the current timestamp, check whether it is within the last 3 seconds (or you can change this number according to the network environment).
If the timestamp parameter is within last 3 seconds, then it means this GET /some-page?success=true request is a result of server redirect. If not, then it's more like a result of "user refreshes the page or bookmarks it".
In server code that handling GET /some-page, render different HTML according to the result of step 3. Display the success message only when current access is a result of server redirect.

How to reuse variables from previous request in the Paw rest client?

I need to reuse value which is generated for my previous request.
For example, at first request, I make a POST to the URL /api/products/{UUID} and get HTTP response with code 201 (Created) with an empty body.
And at second request I want to get that product by request GET /api/products/{UUID}, where UUID should be from the first request.
So, the question is how to store that UUID between requests and reuse it?
You can use the Request Sent Dynamic values https://paw.cloud/extensions?extension_type=dynamic_value&q=request+send these will get the value used last time you sent a requst for a given request.
In your case you will want to combine the URLSentValue with the RegExMatch (https://paw.cloud/extensions/RegExMatch) to first get the url as it was last sent for a request and then extract the UUID from the url.
e.g
REQUEST A)
REQUEST B)
The problem is in your first requests answer. Just dont return "[...] an empty body."
If you are talking about a REST design, you will return the UUID in the first request and the client will use it in his second call: GET /api/products/{UUID}
The basic idea behind REST is, that the server doesn't store any informations about previous requests and is "stateless".
I would also adjust your first query. In general the server should generate the UUID and return it (maybe you have reasons to break that, then please excuse me). Your server has (at least sometimes) a better random generator and you can avoid conflicts. So you would usually design it like this:
CLIENT: POST /api/products/ -> Server returns: 201 {product_id: UUID(1234...)}
Client: GET /api/products/{UUID} -> Server returns: 200 {product_detail1: ..., product_detail2: ...}
If your client "loses" the informations and you want him to be later able to get his products, you would usually implement an API endpoint like this:
Client: GET /api/products/ -> Server returns: 200 [{id:UUID(1234...), title:...}, {id:UUID(5678...),, title:...}]
Given something like this, presuming the {UUID} is your replacement "variable":
It is probably so simple it escaped you. All you need to do is create a text file, say UUID.txt:
(with sample data say "12345678U910" as text in the file)
Then all you need to do is replace the {UUID} in the URL with a dynamic token for a file. Delete the {UUID} portion, then right click in the URL line where it was and select
Add Dynamic Value -> File -> File Content :
You will get a drag-n-drop reception widget:
Either press the "Choose File..." or drop the file into the receiver widget:
Don't worry that the dynamic variable token (blue thing in URL) doesn't change yet... Then click elsewhere to let the drop receiver go away and you will have exactly what you want, a variable you can use across URLs or anywhere else for that matter (header fields, form fields, body, etc):
Paw is a great tool that goes asymptotic to awesome when you explore the dynamic value capability. The most powerful yet I have found is the regular expression parsing that can parse raw reply HTML and capture anything you want for the next request... For example, if you UUID came from some user input and was ingested into the server, then returned in a html reply, you could capture that from the reply HTML and re-inject it to the URL, or any field or even add it to the cookies using the Dynamic Value capabilities of Paw.
#chickahoona's answer touches on the more normal way of doing it, with the first request posting to an endpoint without a UUID and the server returning it. With that in place then you can use the RegExpMatch extension to extract the value from the servers's response and use it in subsequent requests.
Alternately, if you must generate the UUID on the client side, then again the RegExpMatch extension can help, simply choose the create request's url for the source and provide a regexp that will strip the UUID off the end of it, such as /([^/]+)$.
A third option I'll throw out to you, put the UUID in an environment variable and just have all of your requests reference it from there.

How to apply the PUT verb in a REST request?

I'm working on a REST server. I have an order RESOURCE.
From my understanding the PUT verb should create a new order based on the URL. My question is: How can this work if the resource is new and you don't know the ID of the new order?
I know the debate about POST vs PUT, but I'm quoting the w3 specs for PUT http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
"If the Request-URI does not point to an existing resource, and that URI is capable of being defined as a new resource by the requesting user agent, the origin server can create the resource with that URI"
In RESTful APIs, PUT is typically used to update a resource or create one if it doesn't exist at the specified URL (i.e. the client provides the id). If the server generates the id, RESTful APIs typically use a POST to create new resources. In the latter scenario, the generated id/url is usually returned or specified in a redirect.
Example: POST /orders/
According to W3C Both PUT and POST can be used for update and/or create.
The basic difference between them is how the server handles the Request-URI. PUT URI identifies the entity and the server should't try to map it to another URL, while POST URI can be a handler for that content. Examples:
It's OK to POST a new order to /order, but not a PUT. You can update order 1 with a PUT or POST to /order/1.
To put it simply POST is for creating and PUT is for updating. If you don't have an ID for an object because it isn't created yet, you should be using a POST. If an object DOES exist and you just don't have the ID for it, you're going to have to search for it using a GET of some kind.
The thing to remember is Idempotence. A PUT (and GET for that matter) is idempotent. Basically meaning, you can hit the same URL over and over and it shouldn't make a difference the 2nd or 3rd time (It edits the data once, and calling it again it doesn't make that change again). However a POST is not idempotent. Meaning, you hit the same URL 3 or 4 times in a row and it's going to keep changing data (creating more and more objects). This is why a browser will warn you if you click back to a POST url.
You say, "don't know the ID of the new order" therefore the following is not true "URI is capable of being defined as a new resource by the requesting user agent", therefore PUT is not appropriate in your scenario.
Where is the confusion? I am of course assuming the Id would be part of the URL.

Cancel an HTTP GET request from Firefox Extension

I have a firefox extension that listens to "http-on-modify-request" and inspects all GET requests coming from firefox. I'd like to be able to cancel the request (say return a fail code to the page) or modify the URI of the request but can't seem to do it. the nsiHttpChannel object just doesn't allow it - for instance
delete httpChannel;
or reseting to an empty request
httpChannel = Components.classes["#mozilla.org/xmlextras/xmlhttprequest;1"].createInstance(Components.interfaces.nsIXMLHttpRequest);
don't work (and you can't modify the URI).
So how do you both intercept and modify http GET requests in a firefox extension.
delete httpChannel; just deletes the variable, sort of like saying httpChannel = undefined;. The request itself is unchanged. Similarly, your second idea just sets the variable to point at a new nsIHttpChannel instance, but the old request is still unchanged.
To modify the request, use its properties and methods. See nsIHttpChannel or nsIChannel or nsIRequest. As you say, you can't modify the URI so you might want to cancel it (see below) and replace it with a new one. I'm not sure exactly how to do that but I imagine one of those three pages has the answer.
To cancel it, use nsIRequest.cancel()

If POST to an URL and how can I tell the client to look at a fragment of the response?

I would like to POST an entity as follows
POST /example.org/MyEntity/100
Based on the passed entity, the server would like to draw the users attention to a particular part of the response using a fragment identifier. e.g.
/example.org/MyEntity/100#InterestingPart
How do I return this new URL to the client. I am assuming I could do some form of redirect using a 3XX response code, but I actually do not want the client to do another request because the only difference between the two URLs is the fragment. At the moment it seems that a 307 return code would be the most appropriate because according to the spec you should not automatically redirect a POST.
Is there are better way?
Update: My client is not limited to the constraints of a web browser. I am just looking at this from the perspective of HTTP.
Update2: Based on my reading of RFC2616, I can see nothing stopping me from returning a 200 and a Location header that contains the fragment identifier. Anyone know of a reason why I cannot do that?
I think the only sensible solution is to have action URL have static fragment identifier, like <form method="post" action="/action#anchored"> and then put an anchor wherever you want user to look at while generating page.
But, to answer the Update2: no, there's no reason to avoid it.
My inclination is to return 201 - and have the location header point to the URI you want the client to GET.
I didn't look, but IIRC nothing dictates that the location header points to the resource created, so it should be spec legal.
You should normally redirect every POST to avoid problems with refreshing the page and the use of the back button. This is known as the PRG (POST Redirect Get) pattern:
http://blog.httpwatch.com/2007/10/03/60-of-web-users-can%E2%80%99t-be-wrong-%E2%80%93-don%E2%80%99t-break-the-back-button/
Although, this does incur the cost of another round trip to the server it makes your web application much more user friendly.
You could then add the fragment onto the redirected URL.
There's an example of PRG with a fragment on this page:
http://www.httpwatch.com/httpgallery/redirection/
POSTing to the URI:
http://example.org/MyEntity/100
implies to me that a MyEntity resource called "100" already exists. If that's the case, why not use PUT instead? Is this an update or a create operation?
An alternative might be:
POST http://example.org/MyEntities
Now your service has a choice to make from at least two possibilities:
Return 201 Created. Set the Location header to be the URI you want the client to use (e.g.: http://example.org/MyEntities/100#InterestingPart). Add the representation of the new resource to the body.
Return 204 No Content. Same as above, but no body. This option requires a subsequent GET to fetch the representation, which sounds like what you're trying to avoid.
Neither approach requires redirection and both can return as specific a URI as you desire.
I am curious though, why is the #InterestingPart significant? Why not just return the entire representation and its URI http://example.org/MyEntities/100 in the Location header - and let clients decide for themselves what's interesting or not? If the answers have something to do with only a small part of the resource being of interest (or being modified) during a request, how feasible would it be to break MyResource into a main resource and one or more subordinate resources? For example:
/MyResources/100/CoolThings
/MyResources/100/CoolThings/42
/MyResources/100/InterestingThings
/MyResources/100/InterestingThings/109

Resources