Backend Development 7 min read

Python Requests Tutorial for API Chained Calls and Automated Testing

This article demonstrates how to use Python's requests library to perform chained API calls—login, create user, retrieve user details, and update user information—while handling exceptions, logging, and environment configuration for robust automated testing.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Python Requests Tutorial for API Chained Calls and Automated Testing

In API automation testing, chained calls are common; for example, a login endpoint returns a token that subsequent endpoints use for authentication, or a created resource ID is needed for update or delete operations. This guide provides a complete practical example using Python's requests library.

1. Scenario Description

Assume a user‑management system with the following APIs:

Login API – returns a token after successful authentication.

Create User API – creates a new user using the token.

Get User Info API – retrieves detailed information by user ID.

Update User API – updates user information by user ID.

2. Implementing Chained Calls

2.1 Preparation

pip install requests

2.2 Test Code

The following code shows how to implement the chained calls:

import requests

# 1. Login API
def login():
    url = "http://example.com/api/login"
    data = {"username": "testuser", "password": "testpass"}
    response = requests.post(url, json=data)
    if response.status_code == 200:
        return response.json().get("token")
    else:
        raise Exception(f"Login failed: {response.text}")

# 2. Create User API
def create_user(token):
    url = "http://example.com/api/users"
    headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
    data = {"name": "John Doe", "email": "[email protected]"}
    response = requests.post(url, headers=headers, json=data)
    if response.status_code == 201:
        return response.json().get("id")
    else:
        raise Exception(f"Create user failed: {response.text}")

# 3. Get User Info API
def get_user(token, user_id):
    url = f"http://example.com/api/users/{user_id}"
    headers = {"Authorization": f"Bearer {token}", "Accept": "application/json"}
    response = requests.get(url, headers=headers)
    if response.status_code == 200:
        return response.json()
    else:
        raise Exception(f"Get user info failed: {response.text}")

# 4. Update User API
def update_user(token, user_id):
    url = f"http://example.com/api/users/{user_id}"
    headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
    data = {"name": "John Doe Updated", "email": "[email protected]"}
    response = requests.put(url, headers=headers, json=data)
    if response.status_code == 200:
        return response.json()
    else:
        raise Exception(f"Update user failed: {response.text}")

# Test case
def test_user_flow():
    print("Starting user flow test...")
    try:
        token = login()
        print(f"Login successful, token: {token}")
        user_id = create_user(token)
        print(f"User created, ID: {user_id}")
        user_info = get_user(token, user_id)
        print(f"User info retrieved: {user_info}")
        updated_info = update_user(token, user_id)
        print(f"User info updated: {updated_info}")
        print("User flow test completed!")
    except Exception as e:
        print(f"Test failed: {e}")

if __name__ == "__main__":
    test_user_flow()

3. Code Explanation

The login function sends a POST request and returns the token; the create_user function uses the token to create a user and returns the new user ID; get_user retrieves details using the token and ID; update_user modifies the user data. The test_user_flow function orchestrates these steps in order.

4. Precautions

Exception handling: each API call includes error checking and raises exceptions on failure to keep the test stable.

Logging: use Python's logging module to record request and response details for troubleshooting.

Test data management: store credentials and other data in configuration files or environment variables to ensure security and maintainability.

Environment switching: support multiple environments (dev, test, prod) by configuring base URLs externally.

5. Summary

Using the requests library, you can easily implement chained API calls for automated testing. Combined with Python's exception handling and logging, this approach ensures test stability and maintainability.

backendautomationtestingRequestsapi-testing
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.