How to get and send cookies in REST API's

Hi,

Just wanted to post out here a topic that i had a little challenge with in case there's anyone out there in the same situation. 

The case scenario is that i have a mobile application that all the user data is being managed via a backend that exposes APIs. The requirement was that these REST APIs returned in each call a set of cookies that i needed to append in the next API call the user made. So the way that I did this is by using the OnBeforeRequest and OnAfterResponse methods to make it work globally.

The main purpose is to catch the Cookies a RestAPI response gives you and then send them back onthe request each time you are about to call an API. This is mainly when the production server has multiple balancers and cookies are necessary to identify in which balancer the user is actually at in the moment.


STEP 1

Use the OnAfterResponse to catch the first set of Cookies



Cookies are basically Headers but with a name scheme of "Response.Headers.Current.Name = "Set-Cookie". (The code is not perfect, You can do a List-filter of Set-Cookie and then use the for-each) 


STEP 2

Cookies have a couple of metadata that comes with it in a RESTAPI. For example:

"Set-Cookie: SMSESSION=KJGSFUIYGKJCDBSJ; path=/; domain=.myapp.com,JSESSIONID=1~bqoqznDLvja8qNC4eYc5vGn3; Path=/app/qw-sx-trx/rest/6.2/trx/transaction/acc; Domain=myappdomain.com;HttpOnly;Secure"

As you can see, a little processing is needed to capture the necessary data to append the cookie in the next call. That's why i used some regex.


STEP 3

Run a string split out of the previous regex



STEP 4

Run a for-each loop of the result of the previous string-split and run another string-split of the current value iterration



STEP 5

Do another string-split base on the previous one


STEP 6

Use the SetCookie action that outsystems HTTPRequestHandler module provides and append the ";secure;httponly" if it applies.



STEP 7

Use the OnBeforeRequest on other module or the same module to catch the SetCookie you just used in step 6. Use the RequestHeader action filtering by "cookie" to get your cookie and do a List append to the header so you can send it in the call you are doing.

Good Sharing Luis