Allowing the user to change application state (f.ex. language) in a RESTful web-app
I am currently re-writing an old web-application and I want it to be RESTful. Now, one important philosophy behind a RESTful app, is that each request to the end-point has to be stateless.
With the application I am aiming for a common codebase for the API as for normal browsing. In other words, I want to avoid special URLs like http://api.domain.tld
or http://domain.tld/api
. I intend to interpret the HTTP Accept
header for this.
One challenge I came up with, are request parameters, that a user browsing the page usually only chooses once. A good example for this is the language. Again, I can use the Accept-Language
header to pick an initial language. But what if the user wishes to change this? It would be unusable if the user needed to switch the language after each request.
In my opinion, this is really a request parameter, and should be passed on as such. For example: http://domain.tld/resource?lang=en
. So once the user switched the language, I would need to append this parameter to each URL on the page.
In a way, this makes the browsing-session stateful. Are there any "best practices" for this? How would you approac开发者_运维技巧h this. One idea I have, is to store these "global" parameters in the session, but add them to each URL nevertheless. If only to make the API easily discoverable.
On a sidenote: I am currently building the web-page using Flask which provides a method url_for
to build URLs. I am considering overriding this, so each generated URL will have the parameter. But this is not a Flask specific problem. This is something most RESTful services should consider, so I will tag it neither with python, nor flask!
State Transfer
REST doesn't require each request to be stateless. The requirement is that the server does not have to manage state on behalf of the client. In effect, each request has to carry sufficient state to allow the server to process it.
Your approach, providing the user language is perfectly sensible. Others might prefer to retrieve it from a shared database but this can have some scalability concerns.
精彩评论