Master the art of professional API testing. Learn how to use Postman to automate the login flow and test your public and private endpoints without manual copy-pasting.
1. Setting Up the Environment
In Postman, create a new Environment (top-right dropdown) named "Django Dev". Add the following variables:
url: Set tohttp://127.0.0.1:8000/apiaccess_token: Leave this blank; we will fill it automatically.
Make sure you select this environment in the dropdown before proceeding.
2. Test 1: Public URL (No Auth)
Create a GET request to {{url}}/public/. No headers are required.
Expected Result: 200 OK - "Public access allowed!"
3. Test 2: Login & Automation Script
Create a POST request to {{url}}/login/. In the Body tab, select raw -> JSON and enter your username and password.
{
"username": "your_django_user",
"password": "your_secret_password"
}
Now, click the Scripts (or Tests) tab and add this code:
const response = pm.response.json();
if (response.token) {
pm.environment.set("access_token", response.token);
console.log("Token automatically saved!");
}
Click Send. Postman will now "grab" the token and save it to your environment variables.
4. Test 3: Private URL (Using the Token)
Create a GET request to {{url}}/private/. Instead of typing a long key, use the variable.
Go to the Headers tab and add:
- Key:
Authorization - Value:
Token {{access_token}}
Expected Result: 200 OK - "Hello [Your Username], this is private!"
5. Test 4: Logout (Invalidation)
Create a POST request to {{url}}/logout/ using the same Authorization header from Test 3.
Action: Click Send. The token is now deleted on the server.
Verification: If you try to run Test 3 again, you will receive a 401 Unauthorized error, proving the logout was successful.
Testing Flow Summary
| Step | Action | Postman Variable Used |
|---|---|---|
| 1. Login | POST credentials | Sets {{access_token}} |
| 2. Access | GET Private Data | Reads {{access_token}} |
| 3. Logout | POST Logout | Deletes token on server |