Storing and reusing cookies in Postman is a crucial feature, especially when working with web services and API testing, where you often need to maintain user authentication or track session information. Below are the steps to effectively manage cookies in Postman:
1. Automatic Cookie Storage
Postman automatically stores cookies returned in the response by default. This means when you send a request to the server and the response includes a Set-Cookie header, Postman will automatically save these cookies in its Cookie Manager. These cookies will be used for subsequent requests to the same domain.
2. View and Manage Cookies
To view and manage cookies stored in Postman, you can:
- Click the Cookies icon (a small cookie icon) in the top-right corner of the Postman interface.
- This opens the Cookie Manager, listing all stored cookies.
- Here, you can view cookie details such as value, domain, path, and expiration time.
- You can also manually add, modify, or delete cookies.
3. Use Environment Variables to Store and Use Cookies
Although Postman can automatically handle cookies, in complex scenarios, you may need to manually set cookies. You can use environment variables to store specific cookie values and reference them in request headers when needed:
- First, create an environment variable in the "Environment" settings, for example named
myCookie. - After sending a request to obtain the cookie, manually copy the cookie value to this environment variable.
- In subsequent requests, set the
Cookieheader in the request and use{{myCookie}}to reference the cookie value stored in the environment variable.
4. Script Automation for Handling Cookies
Postman's Pre-request Script and Tests features allow you to write JavaScript code to handle cookies programmatically:
- Pre-request Script: Executed before sending a request, it can read cookies from environment variables and add them to the request header.
- Tests: Executed after receiving a response, it can parse the Set-Cookie header from the response and update the cookie value in the environment variable.
Example
Suppose the login API response includes a cookie named sessionToken, which needs to be used in subsequent requests:
javascript// Tests script to get and store the cookie var cookies = pm.response.headers.get('Set-Cookie'); pm.environment.set('sessionToken', cookies); // Pre-request Script to use the stored cookie var token = pm.environment.get('sessionToken'); pm.request.headers.add({ key: 'Cookie', value: `sessionToken=${token}` });
This approach flexibly handles various test scenarios requiring cookie state maintenance, making API testing more closely resemble real user behavior.