Verify backend logic through API testing for user login
Preconditions (2)
✅ Expected Result: Response status code is 200, response body contains 'success': true and a non-empty 'token' string
import requests import pytest class TestUserLoginAPI: base_url = "https://api.example.com" def test_user_login_success(self): url = f"{self.base_url}/login" payload = {"username": "testuser", "password": "Test@1234"} response = requests.post(url, json=payload) # Assert status code is 200 assert response.status_code == 200, f"Expected status code 200 but got {response.status_code}" json_data = response.json() # Assert 'success' key is True assert json_data.get('success') is True, "Expected 'success' to be True in response" # Assert 'token' key exists and is a non-empty string token = json_data.get('token') assert isinstance(token, str) and token.strip() != "", "Expected a non-empty 'token' string in response"
This test script uses the requests library to send a POST request to the login API endpoint.
We check the HTTP status code to confirm the request succeeded (200 means OK).
Then we parse the JSON response and verify the backend logic by asserting the 'success' flag is true and a valid token is returned.
Assertions have clear messages to help understand failures.
This test directly validates backend logic by checking the API response without UI involvement.
Now add data-driven testing with 3 different sets of user credentials: one valid, one invalid password, one non-existent user
response = requests.post('https://api.example.com/login', json={'user':'test', 'pass':'1234'})
print(response.status_code)const response = await fetch('https://api.example.com/items', { method: 'GET' });
const data = await response.json();
console.log(data.items.length);TypeError: Cannot read property 'length' of undefined. What is the likely cause?Pass the test and this pattern moves unknown