How to request an interface (based on cookies) that needs to be logged in to access — apipost

When developing and debugging interfaces in the background, we often encounter interfaces that can only be requested after logging in.

For example: get the favorite list of login users. At this time, we need to simulate the login state for interface debugging. As shown in the figure:


Today, we will explain how to use the environment variable of apipost to solve the interface dependency that requires login before request.

Apipost offers two options:

##Scheme I: enable global cookie

Apipost provides the function of opening global cookies. The opening path is as follows:

Bottom right cookie Manager - open global cookie button


After opening, after we request the login interface, the subsequent interfaces will share the “logged in” status, that is, the cookies returned by the login interface are shared.

As follows:

###Step 1: request login interface


###Step 2: when accessing other interfaces, they are in login status


##Scheme II: using environment variables, first request the login interface, and then request the subsequent interface

This scheme is used when * * global cookie function is turned off.

###1. Request to log in to the interface and assign the response cookie to the variable:

In order to be in the login status, you need to request the login interface first. This is to simulate the user’s login behavior and obtain the required login parameters (cookies here).

Set the phpsessid returned by the login interface (this is the sessionid. Phpsessid is the sessionid variable name for PHP as the back-end interface, and the variable names of other languages may be different) as the environment variable.

apt.variables.set("login_ var", response.cookies["PHPSESSID"]);

Note: for more response result binding variables, please refer to the “response and assertion” section and the “post execution script” section.


###2. Call variables and manually add cookie parameters to the header

Then return to the collection interface, enter the header option, select the cookie for the parameter value, and enter the parameter value: phpsessid = {{login_ var}}。

This is to use the cookie returned by the login interface to forge the phpsessid of the request.

As shown in the figure:


Alternatively, you can define a global header so that you don’t have to set every interface:



###Login implementation principle

Use apipost to send cookies to enable the server to identify the cookies of logged in users.