Hone logo
Hone
Problems

Mastering HTTP Sessions with Python Requests

Many web applications require you to maintain state across multiple HTTP requests, such as login sessions or shopping carts. The requests library in Python provides Session objects to handle this efficiently. This challenge will test your ability to create and utilize a Session object to manage cookies and maintain state across a series of HTTP requests.

Problem Description

Your task is to write a Python program that uses the requests library to interact with a hypothetical web service. You will need to:

  1. Create a requests.Session object.
  2. Perform a POST request to a "login" endpoint, simulating user authentication. This endpoint will set a specific cookie that identifies the logged-in user.
  3. Perform a GET request to a "profile" endpoint. This request should automatically use the cookie set during the login process, demonstrating session persistence.
  4. Perform a GET request to a "data" endpoint. This request should also leverage the existing session, ensuring the user is still considered logged in.

Your program should capture the responses from these requests and verify that the session management is working as expected.

Key Requirements:

  • Use requests.Session() to create a persistent session.
  • The Session object should automatically handle cookie persistence between requests.
  • Your program should successfully simulate a logged-in state and access protected resources.
  • The output should clearly indicate the success or failure of each step.

Expected Behavior:

When the program is run, it should:

  • Print a message indicating the start of the session.
  • Print the status code and content of the login response.
  • Print the status code and content of the profile response.
  • Print the status code and content of the data response.
  • If the login is successful and the session is maintained, the profile and data endpoints should return content indicating a logged-in user.

Edge Cases:

  • What happens if the login fails (e.g., incorrect credentials)? The program should gracefully handle this, although for this challenge, we will assume successful login.
  • The service might have rate limiting or other server-side behaviors not explicitly modeled here. Focus on the client-side session management.

Examples

For the purpose of this challenge, let's assume a mock API service is available at http://localhost:5000.

Mock API Endpoints:

  • POST /login: Expects username and password in JSON payload. Sets a sessionid cookie upon successful login.
    • Success Response (200 OK): { "message": "Login successful" }
    • Failure Response (401 Unauthorized): { "message": "Invalid credentials" }
  • GET /profile: Requires a valid sessionid cookie.
    • Success Response (200 OK): { "username": "user123", "email": "user123@example.com" }
    • Failure Response (401 Unauthorized): { "message": "Unauthorized. Please log in." }
  • GET /data: Requires a valid sessionid cookie.
    • Success Response (200 OK): { "items": ["item1", "item2", "item3"] }
    • Failure Response (401 Unauthorized): { "message": "Unauthorized. Please log in." }

Example 1: Successful Session Management

Input (Simulated API behavior):

  • A requests.Session object is created.
  • POST /login with {"username": "user123", "password": "password123"} is made. The API sets sessionid=abc123xyz.
  • GET /profile is made. The sessionid cookie is sent.
  • GET /data is made. The sessionid cookie is sent.

Output (Expected program output):

Starting HTTP session...
Attempting to log in...
Login Status Code: 200
Login Response: {'message': 'Login successful'}

Fetching profile information...
Profile Status Code: 200
Profile Response: {'username': 'user123', 'email': 'user123@example.com'}

Fetching data...
Data Status Code: 200
Data Response: {'items': ['item1', 'item2', 'item3']}

Session management successful!

Constraints

  • You must use the requests library.
  • The mock API will be running on http://localhost:5000. (For actual execution, you would need a mock server set up or a real service that behaves this way.)
  • Your program should complete within a reasonable time, implying efficient use of the session object.

Notes

  • The requests.Session object is powerful. It persists cookies across requests and can also be used to configure default headers, authentication, and other settings for all requests made through that session.
  • Consider how you will structure your Python code to make sequential calls and process their responses.
  • You can use a library like Flask or FastAPI to set up a simple mock server locally if you wish to fully test this challenge end-to-end. For the purpose of demonstrating the client-side logic, you can also mock the responses.
Loading editor...
python