Can I change the headers of the HTTP request sent by the browser? - rest

I'm looking into a restful design and would like to use the HTTP methods (POST, GET, ...) and HTTP headers as much as possible. I already found out that the HTTP methods PUT and DELETE are not supported from the browser.
Now I'm looking to get different representations of the same resource and would like to do this by changing the Accept header of the request. Depending on this Accept header, the server can serve a different view on the same resource.
Problem is that I didn't find a way to tell my browser to change this header.
The <a..> tag has a type attribute, that can have a mime type, looked like a good candidate but the header was still the browser default (in Firefox it can be changed in about:config with the network.http.accept.default key).

I would partially disagree with Milan's suggestion of embedding the requested representation in the URI.
If anyhow possible, URIs should only be used for addressing resources and not for tunneling HTTP methods/verbs. Eventually, specific business action (edit, lock, etc.) could be embedded in the URI if create (POST) or update (PUT) alone do not serve the purpose:
POST http://shonzilla.com/orders/08/165;edit
In the case of requesting a particular representation in URI you would need to disrupt your URI design eventually making it uglier, mixing two distinct REST concepts in the same place (i.e. URI) and making it harder to generically process requests on the server-side. What Milan is suggesting and many are doing the same, incl. Flickr, is exactly this.
Instead, a more RESTful approach would be using a separate place to encode preferred representation by using Accept HTTP header which is used for content negotiation where client tells to the server which content types it can handle/process and server tries to fulfill client's request. This approach is a part of HTTP 1.1 standard, software compliant and supported by web browsers as well.
Compare this:
GET /orders/08/165.xml HTTP/1.1
or
GET /orders/08/165&format=xml HTTP/1.1
to this:
GET /orders/08/165 HTTP/1.1
Accept: application/xml
From a web browser you can request any content type by using setRequestHeader method of XMLHttpRequest object. For example:
function getOrder(year, yearlyOrderId, contentType) {
var client = new XMLHttpRequest();
client.open("GET", "/order/" + year + "/" + yearlyOrderId);
client.setRequestHeader("Accept", contentType);
client.send(orderDetails);
}
To sum it up: the address, i.e. the URI of a resource should be independent of its representation and XMLHttpRequest.setRequestHeader method allows you to request any representation using the Accept HTTP header.
Cheers!
Shonzilla

I was looking to do exactly the same thing (RESTful web service), and I stumbled upon this firefox addon, which lets you modify the accept headers (actually, any request headers) for requests. It works perfectly.
https://addons.mozilla.org/en-US/firefox/addon/967/

I don't think it's possible to do it in the way you are trying to do it.
Indication of the accepted data format is usually done through adding the extension to the resource name. So, if you have resource like
/resources/resource
and GET /resources/resource returns its HTML representation, to indicate that you want its XML representation instead, you can use following pattern:
/resources/resource.xml
You have to do the accepted content type determination magic on the server side, then.
Or use Javascript as James suggests.

ModHeader extension for Google Chrome, is also a good option. You can just set the Headers you want and just enter the URL in the browser, it will automatically take the headers from the extension when you hit the url. Only thing is, it will send headers for each and every URL you will hit so you have to disable or delete it after use.

Use some javascript!
xmlhttp=new XMLHttpRequest();
xmlhttp.open('PUT',http://www.mydomain.org/documents/standards/browsers/supportlist)
xmlhttp.send("page content goes here");

Related

Is body required in PUT request?

I want to design my REST endpoint for enabling or disabling a user
My thought is to use PUT without body, with this URLs:
PUT /.../users/{userName}/enable
PUT /.../users/{userName}/disable
Is it possible to use PUT without a body?
Do you have any other suggestions?
Is body required in PUT request?
No - a PUT request with an empty body is how we would tell a web server that we want the representation of a resource to be zero bytes long.
PUT /example HTTP/1.0
Content-Type: text/plain
Content-Length: 0
I want to design my REST endpoint for enabling or disabling a user
A bit of prior art that you might consider is the github starring API, which uses PUT with an empty body to turn on a star, and DELETE to turn off a star.
Note that both requests use the same URI - that's appropriate because we want general purpose cache invalidation to "just work".
It may be helpful to be clear in your mind the differences between the semantics of the message ("please save this empty document on the web server") and the business side effects ("enable the user"). See Webber 2011.
Short answer: No.
Personally, I have also used empty PUT requests when merely updating a resource using an idempotent action - like toggling enable/disable.
Possible duplicate of: Is an HTTP PUT request required to include a body?

How do APIs receive the request's method, body, and headers?

The query URL / endpoint below seems to successfully make a request to the API resource and returns a JSON response:
https://wikimedia.org/api/rest_v1/metrics/pageviews/per-article/en.wikipedia/all-access/all-agents/Albert_Einstein/daily/2015100100/2015103100
Given that a request is made up of not only the URL, but also of a method, headers, and body, could someone explain how the API knows which method to use, as well as how the headers and body get transmitted (if they did exist)?
Given that a request is made up of not only the URL, but also of a method, headers, and body, could someone explain how the API knows which method to use, as well as how the headers and body get transmitted (if they did exist)?
If I'm understanding your question correctly... the API doesn't know these things, the client knows these things.
Which is to say when I'm looking at your question in my web browser, what I'm really looking at is the web browsers interpretation of an HTML document. Because the web browser speaks HTML, it knows what <a href="..."> means; that the quoted text is an identifier for another resource that I the use might want to navigate to.
The browser also knows RFC 3986, so it knows how to parse the quoted string and extract from it the protocol, the host, and the target uri.
Because the browser also knows about https, it knows which port number it should default to when the port isn't specified.
Because the browser knows HTTP, it knows how to construct a valid HTTP request, and the semantics of the required and optional headers it might want to attach.
Because HTTP follows the REST architectural style, we also know that the interface is uniform -- all HTTP resources use the same semantics. So the browser doesn't need to know what the identifier is in order to know that GET, HEAD, OPTIONS are all safe. Similarly, the rules for authentication, caching, content-negotiation, and so on are all the same, so the browser can craft the appropriate headers as it generates the request.
For instance, the browser knows that it is itself HTML capable, so it includes headers that communicate a preference for an HTML or XHTML+xml representation of the resource, if one is available.
Were I to instead switch to the command line, I could use curl(1) to generate the http request instead, which would produce an HTTP request with different headers.
The browser (and curl) know not to send a body with a HEAD or GET request because the HTTP specification explains that the payload of a GET or HEAD request has no defined semantics.
On the API side of the conversation, the server knows about HTTP, so knows how to correctly interpret the bytes of the HTTP request. Thus, the server knows where to look in the request for the HTTP method, the target URI, the headers that may (or may not) modify the context of the request, and so on. The implementation can then do whatever it likes with that information, and construct a suitable HTTP response (in effect, lifting into the headers of the response the metadata in a representation that can be understood by all of the general purpose components participating in the conversation.

How to deal with this situation building a REST API?

I got this problem, I have built a rest api and I don't know how to deal with this:
When the javascript client (Marionette.js) is in charge of making the views, I don't have problems, because as it is known, it just requests an url (e.g. example.com/user/37), the server retrieves a json with {id:'37', name:'Peter', age:'24'} (there is one controller class named User) and Marionette shows that data in the view. But if the user enter to example.com/user/37 by the browser it will show just {id:'37', name:'Peter', age:'24'} without any view. What can I do if I want to see the same view in both cases?
If you're trying to serve up HTML or JSON from the same endpoint then your server should be making that decision based on the request's Accept header. If the request's Accept header is application/json then your server should return just the JSON ortherwise return the HTML.
You can see that SoundCloud uses the same technique for returning XML or JSON from their API:
Resources are returned as XML by default, or JSON if a .json extension is appended to the resource URI. We encourage you to use JSON. You can also send an appropriate Accept header specifying the format you would like. For example, a request with the header Accept: application/json will return resources represented as a JSON document.
What you are trying to do is pratically impossible.
why ?
When your first enter the url example.com it's the server that responds with all the artifacts that compose your application (html, js, css ...) and the browser display it.
Now, when you enter ther url example.com/user/37 the server only sends the JSON data without any html, js or css, so the browser display the raw data he received.
What you are trying to do is to force the server to give two responses (JSON or html/js/css) depending on the user request.
You can do it, but it would be so complicated that's not worth the efforts.

Is it possible to change/modify properties of a CR using OSLC_CM?

Is it possible to modify a property of a change request by using the OSLC-CM REST API of a change management system. The system that I'm trying to achieve that is Rational Change.
I can browse and query via the REST API, but to modify anything I need to resort to command line which is rather slow.
Is there a way?
BR,
Pawel
To update resources using the OSLC-CM REST API you simply just can use HTTP PUT. In order to do this, you'll first need the URL of the Change Request.
The steps to achieve this (using any HTTP client) are:
acquire URL for Change Request (usually done by query, or stored reference, etc)
Perform an HTTP GET on that URL, specifying a format for use in editing. This is done using 'Accept' header, some typical values would be 'application/xml', 'application/json' or 'application/rdf+xml'.
Note, it is a good idea to set the header 'OSLC-Core-Verson: 2.0' as well to ensure you are working with the 2.0 formats.
Once you have fetched the resource, modify the property to the value you want.
Using HTTP PUT, send the modified resource in the content body to the same URL you fetched the resource from.
Additionally you will most likely need to pass along some additional headers to help the server detect any possible conflict.
You should get back a 200 (OK) or 204 (No content) response on success.
An optimization would be to do the same steps as above but only request the properties of interest and only send them by using the selective properties feature of OSLC.
So I've finally got it working with some help from googlegroups
To recap what I've done so that someone else might benefit too (I really have searched for it and the IBM documentation is as in most of the cases not helping):
So to modify PR/CR' implement_actual_effort attribute on the Rational Change server the following procedure was successful (using Firefox REST plugin):
1. In Headers set: Accept to application/xml, Content-Type to application/xml
Put the oslc address of the cr i URL in my case it was:
http://[IP:PORT]/change/oslc/db/[DB hex ID]/role/User/cr/[web_encoded_name_of_the_CR]?oslc_cm.properties=change:implement_actual_effort
(note in browser http://[IP:PORT]/change/oslc/db/[DB hex ID]/role/User/cr/[web_encoded_name_of_the_CR] will open change page of the CR/PR)
In REST client set Method to GET and press SEND
Click on the Response Body (RAW), copy xml Body
Change Method to PUT, change the value of the attribute (in the xml in Body window)
Press SEND
Attribute should have been changed right now, and the response should be similiar to what you've sent, with the attribute showing the change.
Note that to change an attribute (called property from oslc point of view) one has to provide ?oslc_cm.properties=[properties delimited with comma]
and in the request body xml the same properties have to be present, if I remember correctly if the property isn't mentioned in the xml it will be set to default
I hope this helps someone
BR,
Pawel

Responding appropriately with a 415 error in a RESTful web app

I am building a web application which can accept resource representations via PUT, POST and PATCH in both x-www-form-urlencoded and JSON formats. If I receive a request body in another format, I would like to send a 415 response, plus some additional data declaring what formats I do accept (in a similar manner to the 405 response's mandatory Allow: header). I have seen on one answer at HTTP 406 and 415 error codes where the person answering did not know if there was such a mechanism defined, RFC 2616 mentions nothing in this regard, and some cursory Googling turns up nothing either.
I would like to just use Accept: even though that is defined as a request header. It seems most appropriate just to re-use it for this response. Do folks agree? Does anyone have a better suggestion?
Edit: I have since found Specify supported media types when sending "415 unsupported media type" which asks specifically if there is a standard for this. The correct and accepted answer was basically no, but the respondant there also had the same idea as me, that Accept would be a good header to use to provide this information. This prompted a message from Julian Reschke to the HTTP Working Group asking if it should be defined what sending an Accept: header in a response should mean. That email only received one response, which agreed that it was needed and that Accept seemed appropriate.
Note that I am not asking if I am permitted to send an Accept header, any header is allowed to be sent in either direction, but only those defined in the spec have meaning (semantics) to intermediaries, and also, any unexpected headers not prefixed with X- might clash with future versions of HTTP. This doesn't bother me.
As you said, Accept is a request-header. It is wrong to use it in a response.
To quote Wikipedia,
Content negotiation is a mechanism defined in the HTTP specification that makes it possible to serve different versions of a document (or more generally, a resource representation) at the same URI, so that user agents can specify which version fit their capabilities the best.
So it is the client who says in the request what media types he can Accept. If the server is not able to deliver this media type he responds with 406 Not Acceptable.
Since the client must be able to deal with the returned representation of the requested resource, it should specify which media types it can understand. It can specifiy multiple media types:
Accept: application/json, application/xml, x-www-form-urlencoded
If the client really wants to accept any media type, it can set
Accept: */*
The server will set a proper Content-Type response header even for such a request.
You receiving an unrecognized Content-Type will most probably be from a developer currently implementing a client to your service. Since there does not exist a mechanism for a server to advertise its supported content types, you might as well mention in the message body what types you do support.
I'm not aware of any standard mechanism to do this but you may be able to slightly re-purpose the Alternates header http://www.ietf.org/rfc/rfc2295.txt to do what you want.