smartyfy.mrindigi.com

Python Master Course V2 — 091. How the Web Works

SMARTYFY ACADEMY · PYTHON MASTER COURSE V2 · MODULE 09 — WEB AND API ENGINEERING · LESSON 091 / 200

How the Web Works

Estimated study: 80–110 minutes · Prerequisite: preceding lesson, functions, exceptions and structured data.

Course hub

Video lesson

Video not yet available; this area is reserved for a verified video link or player.

Learning outcomes

Understand client-server communication. Explain the technical mechanism, interpret outputs, diagnose failures, test edge cases and apply the skill in a realistic system.

Understand and apply: How the Web Works

DNS resolves hostnames; TLS protects HTTPS transport; requests carry methods, paths, headers and optional bodies; responses carry status, headers and content.

Follow one request from a URL to a result

A web client asks a server for a resource. A URL identifies the scheme, host, optional port, path and query. The scheme helps select the transport; the host identifies the service; the path and query describe the resource being requested. A fragment such as #details is interpreted by the client and is not part of the HTTP request target sent to the server.

Python example

from urllib.parse import urlsplit
url = urlsplit("https://example.org:443/catalog?q=python#details")
print(url.scheme, url.hostname, url.port)
print(url.path, url.query, url.fragment)
target = url.path + ("?" + url.query if url.query else "")
print(target)

Expected output

https example.org 443
/catalog q=python details
/catalog?q=python

Parsing only separates text; it does not resolve a hostname, validate a certificate or send a request. In a simplified fresh HTTPS connection, the client resolves the hostname through DNS, establishes a connection, negotiates TLS and then exchanges HTTP messages. Existing connections, caches and newer HTTP transports can change those individual steps, so this trace is a learning model rather than a claim that every browser repeats the same work.

  1. DNS: obtain an address for the requested hostname, possibly from a cache.
  2. Connection and TLS: establish encrypted communication and verify the server identity for the hostname.
  3. Request: send a method, request target, headers and any permitted body.
  4. Application: route the request, authorize it, read or change data and construct a response.
  5. Response: return status, headers and body; the client validates and presents the result.

A deterministic application-layer exchange

Python example

import json

def local_server(method, path):
    if method != "GET":
        return 405, {"error": "method_not_allowed"}
    if path != "/products/PEN":
        return 404, {"error": "not_found"}
    return 200, {"sku": "PEN", "qty": 3}

status, body = local_server("GET", "/products/PEN")
wire_text = json.dumps(body, sort_keys=True)
print(status)
print(wire_text)
print(json.loads(wire_text)["qty"])

Expected output

200
{"qty": 3, "sku": "PEN"}
3

This function call models routing and response data without opening a network connection. The server-side function chooses a result, serialization turns the dictionary into text, and the client decodes that text before using qty. A real transport adds sockets, TLS, timeouts and header handling around this application boundary. Keeping these layers distinct makes failures easier to diagnose.

A DNS failure occurs before any server HTTP response. A TLS verification failure also differs from an HTTP 404, which means an HTTP server responded that the requested resource was not found. A timeout can happen at several stages. Even a 200 response can contain invalid JSON or an unexpected schema, so transport success is only one check.

HTTPS protects data in transit to the authenticated endpoint; it does not prove the application’s data is correct or grant a user permission to access every record. Cookies and bearer tokens may carry identity-related state across requests even though HTTP itself is stateless. Keep secrets out of query strings because URLs often appear in logs and history.

For the project, draw the five stages above and annotate what each receives and returns. Add one failure at each boundary, label which failures have an HTTP status, and show where JSON parsing occurs. Include one cached or reused-connection path so the diagram does not imply every request needs a fresh DNS lookup and handshake.

Runnable Python example

Requires Python 3.10+. Save as lesson91.py and run using python or python3. The example uses local or in-memory data and makes no external network request.

from urllib.parse import urlsplit
p=urlsplit('https://example.org:443/catalog?q=python')
print(p.scheme,p.hostname,p.path,p.query)

Expected output:

https example.org /catalog q=python

Reasoning walkthrough

Read the imports and setup, identify the data model, then follow each operation until the final result. Change one input and predict the effect before running it. Consider the behavior with empty data, invalid types and missing resources.

Guided real-world project

Diagram a browser-to-server request and response lifecycle.

  1. Write a specification with data schema, required operations and failure conditions.
  2. Implement a minimal solution using small named functions.
  3. Add input validation and deliberate error responses.
  4. Test typical, boundary and invalid inputs.
  5. Verify the result against an independently calculated expectation.
  6. Document setup, limitations and recovery steps.

Acceptance: deterministic tests, correct handling of rejected data, no undocumented destructive behavior, and a clear explanation of architecture. This project is an assignment; its full implementation has not been independently executed.

Common mistakes and debugging

  • Concatenating untrusted input into SQL or URLs without proper encoding and parameterization.
  • Assuming remote services or databases always succeed.
  • Omitting transaction or timeout boundaries.
  • Confusing transport status with validated application data.
  • Testing only success paths and ignoring empty or malformed responses.

To debug, reproduce the failure, inspect the smallest failing input, check types and constraints, and add a regression test.

Practice with explained answers

Make a prediction before opening each answer. Then trace the example and explain the result in your own words.

Is #details sent in the request target?

Need a hint?

Separate the URL into scheme, authority, path, query and fragment. Which part identifies a location inside the returned document?

Show answer and explanation

No. It is a fragment for client-side interpretation. The server receives the path and query, such as /catalog?q=python.

Does urlsplit contact the server?

No. It parses a string locally. DNS, connection setup, TLS and HTTP exchange require separate transport operations.

How is a DNS failure different from 404?

A DNS failure prevents locating the endpoint and produces no HTTP response from it. A 404 is an HTTP response received after the request reached a server.

Does HTTPS guarantee the JSON has the expected fields?

No. TLS protects the connection and verifies endpoint identity. JSON syntax and application schema still need independent validation.

Why call the local_server example a model rather than a real server?

It is an ordinary Python function, with no listening socket or HTTP parsing. It isolates application behavior; the later capstone adds actual local HTTP transport.

Mastery checkpoint

Reproduce the sample, explain the design, complete the guided project, document three test cases and identify a realistic failure mode. No video, certificate or account-synced completion is claimed.

Course hub · Previous lesson 90 in hub · Next lesson 92 when published.

Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.