CodingBowl

Django REST Part 3 - Automating API Testing: Postman Environments & Scripts

Published on 3 Jan 2026 Tech Development
image
Photo by Massimiliano Latella on Unsplash

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 to http://127.0.0.1:8000/api
  • access_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

Meow! AI Assistance Note

This post was created with the assistance of Gemini AI and ChatGPT.
It is shared for informational purposes only and is not intended to mislead, cause harm, or misrepresent facts. While efforts have been made to ensure accuracy, readers are encouraged to verify information independently. Portions of the content may not be entirely original.

image
Photo by Yibo Wei on Unsplash