Web Services – How Session Works in RESTful Web Services

restsessionweb services

In a web services, how does the server know which request belongs to which session?

I know that for a web application, the web server inspects the cookie (or the sessonId query parameter in case cookies are disabled) so it knows which session the request is associated with. But for a request that comes from a rest client, how do the server know?

Best Answer

If you really must have session handling in your API then the client would be responsible to handle the session_id and add it to the URL if required. How exactly to handle this would depend on your technology stack. For example Rails defaults to cookies but (if enabled) would also accept a _session_id parameter as part of the URL.

The relevant information normally stored in the cookie together with the session id then must be handled by the server. In Rails you would have to switch session storage from cookie storage to one of the server options like storing it in the database or memcached with the session_id as key.

But you should really think twice if you want to add this feature to your API. Being stateless will keep your API simpler and easier to maintain. If any possible it is preferable to let the client worry about state and send all necessary information with each request. (like using HTTP basic authentication instead of storing a current user in a session).