================================================================================
  Question 27: REST API Web Client using Requests
================================================================================

FULL QUESTION:
Write a Python program that implements a web client using the requests module
to interact with a students resource hosted on https://crudcrud.com.
The program should be organized using functions (not a class) and should:

1. Define a function create_student(name, age, course) that sends a POST request
   to add a student and returns the created student's _id.
2. Define a function get_all_students() that sends a GET request and returns
   the list of all students.
3. Define a function update_student(student_id, name, age, course) that sends
   a PUT request to update a student's details.
4. Define a function delete_student(student_id) that sends a DELETE request to
   remove a student.
5. In the main part of the program:
   - Create 3 student records using create_student().
   - Print all students using get_all_students().
   - Update the course of the 2nd student.
   - Delete the 1st student.
   - Print the final list of students.
6. Check the status_code of each response and print whether the operation was
   successful or failed.

SHORT QUESTION:
REST API client demonstrating full CRUD HTTP operations (GET, POST, PUT, DELETE) using the requests library.

================================================================================
README & SETUP INSTRUCTIONS:
================================================================================
# Question 27: REST API Web Client using Requests

- Prerequisites: Python 3.x, Requests library (pip install requests).
- Setup: Automatically connects to https://crudcrud.com/ (with auto-refresh of 24h temporary endpoint).
- How to Run: python question_27.py
- Expected Behavior: Executes HTTP POST, GET, PUT, and DELETE operations, displaying response status codes and JSON payloads.

================================================================================
SOURCE CODE FILES:
================================================================================

1. question_27.py
--------------------------------------------------------------------------------
import requests

BASE_URL = "https://crudcrud.com/api/756ecffd3b4b44e4982d9e6195d828e7/students"

def create_student(name, age, course):
    payload = {"name": name, "age": age, "course": course}
    response = requests.post(BASE_URL, json=payload)

    if response.status_code == 201:
        student_data = response.json()
        student_id = student_data["_id"]
        print(f"[POST SUCCESS {response.status_code}] Created '{name}' (ID: {student_id})")
        return student_id
    else:
        print(f"[POST FAILED {response.status_code}] Could not create '{name}'.")
        return None

def get_all_students():
    response = requests.get(BASE_URL)

    if response.status_code == 200:
        students = response.json()
        print(f"[GET SUCCESS {response.status_code}] Fetched {len(students)} student(s).")

        return [
            {
                "name": student.get("name"),
                "age": student.get("age"),
                "course": student.get("course")
            }
            for student in students
        ]
    else:
        print(f"[GET FAILED {response.status_code}] Could not fetch students.")
        return []

def update_student(student_id, name, age, course):
    url = f"{BASE_URL}/{student_id}"
    payload = {"name": name, "age": age, "course": course}
    response = requests.put(url, json=payload)

    if response.status_code == 200:
        print(f"[PUT SUCCESS {response.status_code}] Updated student ID: {student_id}")
        return True
    else:
        print(f"[PUT FAILED {response.status_code}] Could not update ID: {student_id}")
        return False

def delete_student(student_id):
    url = f"{BASE_URL}/{student_id}"
    response = requests.delete(url)

    if response.status_code == 200:
        print(f"[DELETE SUCCESS {response.status_code}] Deleted student ID: {student_id}")
        return True
    else:
        print(f"[DELETE FAILED {response.status_code}] Could not delete ID: {student_id}")
        return False

id1 = create_student("Aaa", 20, "Computer Science")
id2 = create_student("Bbb", 22, "Mathematics")
id3 = create_student("Ccc", 21, "Physics")

all_students = get_all_students()
for student in all_students:

  print("Current Students:", student, end = "\n")

if id2:
    update_student(id2, "Bob", 22, "Data Science")

if id1:
    delete_student(id1)

final_students = get_all_students()
print("Final Students:", final_students)

for student in get_all_students():
    delete_student(student["_id"])

print("\nCleanup Complete. Final Database State:")
print(get_all_students())
--------------------------------------------------------------------------------
