🌱 Junior Track 31 of 31

31. APIs & HTTP Protocol

Understand web communication for backend Python engineering. Master the HTTP/HTTPS request-response lifecycle, headers, cookies, sessions, status codes (2xx, 3xx, 4xx, 5xx), RESTful CRUD verbs (GET, POST, PUT, PATCH, DELETE), and API integration using Python.

👁️ Views: 0
# ==============================================================================
# JUNIOR PYTHON TRACK 31 — APIs & HTTP (urllib.request & HTTP Protocol)
# ==============================================================================
import urllib.request
import json
from typing import Any, Dict, List

class MockHTTPClient:
    """Simulates HTTP Client operations for REST API endpoints."""
    
    def __init__(self, base_url: str):
        self.base_url = base_url.rstrip("/")
        self.headers = {
            "Content-Type": "application/json",
            "Accept": "application/json",
            "User-Agent": "TeachCloud-PythonClient/1.0"
        }

    def format_response(self, status_code: int, body: Dict[str, Any]) -> Dict[str, Any]:
        """Parses status codes into standard API response metadata."""
        status_category = f"{status_code // 100}xx"
        is_success = 200 <= status_code < 300
        return {
            "status": status_code,
            "category": status_category,
            "success": is_success,
            "data": body
        }

    def simulate_get(self, resource_id: int) -> Dict[str, Any]:
        """Simulates a GET request to read a resource."""
        # Mocking server response for ID 1
        if resource_id == 1:
            payload = {"id": 1, "title": "Learn HTTP & APIs", "completed": True}
            return self.format_response(200, payload)
        else:
            return self.format_response(404, {"error": "Resource Not Found"})

    def simulate_post(self, payload: Dict[str, Any]) -> Dict[str, Any]:
        """Simulates a POST request to create a resource."""
        if "title" not in payload:
            return self.format_response(400, {"error": "Missing required field 'title'"})
        
        created = {**payload, "id": 101, "created_at": "2026-09-20T21:15:00Z"}
        return self.format_response(201, created)

if __name__ == "__main__":
    client = MockHTTPClient("https://api.teachcloud.org/v1")
    
    # 1. GET Request Simulation
    get_res = client.simulate_get(1)
    print(f"GET Status: {get_res['status']} | Data: {get_res['data']}")
    
    # 2. POST Request Simulation
    post_res = client.simulate_post({"title": "Build Microservices in Python", "author": "shkar"})
    print(f"POST Status: {post_res['status']} | Data: {post_res['data']}")
🌱 Junior Track 31 Master Reference

31. HTTP Verbs, Status Codes & REST API Design Guide

🌐 HTTP Verbs & RESTful CRUD Mapping

Verb CRUD Operation Idempotent Safe Description & Use Case
GET Read Yes Yes Fetches resources without altering server state.
POST Create No No Submits data payload to create a new record.
PUT Update (Replace) Yes No Replaces entire existing target resource.
PATCH Update (Partial) No / Depends No Modifies specific fields of an existing resource.
DELETE Delete Yes No Removes the target resource from server.

🔢 HTTP Status Code Categories

Range Category Key Examples Developer Context
1xx Informational 100 Continue, 101 Switching Protocols Request received, server continuing process
2xx Success 200 OK, 201 Created, 204 No Content Action successfully received, understood, and accepted
3xx Redirection 301 Moved Permanently, 302 Found, 304 Not Modified Client must take additional action to complete request
4xx Client Error 400 Bad Payload, 401 Unauthorized, 403 Forbidden, 404 Not Found Request contains bad syntax or missing credentials
5xx Server Error 500 Internal Error, 502 Bad Gateway, 503 Unavailable Server encountered exception while attempting request

⭐ Rate Track 31: REST APIs & HTTP Client (1 to 5 Stars)

Your rating is stored directly in the database. Average: 5.0 / 5 (1 rating)

★ ★ ★ ★ ★
← 30. Databases & SQL 🌱 Junior Hub (31 Modules Complete!) 🚀 Practice 100+ Python Questions →