0
0
Testing Fundamentalstesting~15 mins

Why API testing validates backend logic in Testing Fundamentals - Automation Benefits in Action

Choose your learning style9 modes available
Verify backend logic through API testing for user login
Preconditions (2)
Step 1: Send a POST request to https://api.example.com/login with JSON body {"username": "testuser", "password": "Test@1234"}
Step 2: Check the HTTP response status code
Step 3: Check the response body for a success message and a valid authentication token
✅ Expected Result: Response status code is 200, response body contains 'success': true and a non-empty 'token' string
Automation Requirements - pytest with requests library
Assertions Needed:
Assert response status code equals 200
Assert response JSON contains 'success' key with value true
Assert response JSON contains 'token' key with a non-empty string
Best Practices:
Use setup and teardown methods if needed
Use clear and descriptive assertion messages
Handle exceptions for request failures
Keep test data separate from test logic
Automated Solution
Testing Fundamentals
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.

Common Mistakes - 3 Pitfalls
Not checking the HTTP status code before parsing JSON
Hardcoding test data inside the test method
Not handling request exceptions
Bonus Challenge

Now add data-driven testing with 3 different sets of user credentials: one valid, one invalid password, one non-existent user

Show Hint