Python Master Course V2 — 092. HTTP Fundamentals
SMARTYFY ACADEMY · PYTHON MASTER COURSE V2 · MODULE 09 — WEB AND API ENGINEERING · LESSON 092 / 200
HTTP Fundamentals
Estimated study: 80–110 minutes · Prerequisite: preceding lesson, functions, exceptions and structured data.
Video lesson
Video not yet available; this area is reserved for a verified video link or player.
Learning outcomes
Distinguish methods, status codes and headers. Explain the technical mechanism, interpret outputs, diagnose failures, test edge cases and apply the skill in a realistic system.
Understand and apply: HTTP Fundamentals
GET retrieves, POST typically creates or processes, PUT replaces, PATCH partially updates and DELETE removes. Idempotency and caching depend on method and application behavior.
Separate method intent, status and representation
An HTTP request method expresses the intended operation. GET retrieves a representation, POST submits data for processing, PUT replaces the state of a target resource, PATCH applies a partial change and DELETE requests removal. APIs define their precise resource contracts, but method semantics should remain predictable rather than treating every operation as an arbitrary POST.
A response status summarizes the outcome. 200 means successful handling with the applicable response semantics; 201 identifies creation and commonly includes a Location header; 204 has no response content. Client-error statuses include 400 for a bad request, 401 for missing or invalid authentication, 403 for refusal to fulfill an understood request, 404 for a missing resource and 409 for a conflict with current state. A 5xx response indicates server-side failure, not an instruction to retry blindly.
Illustrative HTTP/1.1 request and response
GET /products/PEN HTTP/1.1
Host: example.org
Accept: application/json
HTTP/1.1 200 OK
Content-Type: application/json
Connection: close
{"sku":"PEN","qty":3}
Accept states what representation the client wants. Content-Type describes the representation actually carried in a message body. Setting Accept does not prove the server returned JSON; inspect the response Content-Type and body. Header names are case-insensitive. This simplified response uses connection closing to delimit the body; real transports manage framing and protocol details for you.
Safe and idempotent are different properties
A safe method asks for no state-changing effect, though servers may still log the request. An idempotent method has the same intended server effect when repeated as when sent once. GET is safe and idempotent. PUT and DELETE are idempotent by their defined semantics but are not safe. POST is not generally idempotent; an application can add a documented idempotency-key contract for particular operations.
Idempotency does not require identical response codes or forbid audit logs. Deleting an existing product may return 204, while repeating the request may return 404; the intended final state is still absence. In contrast, “decrease stock by three” repeated twice usually removes six and requires special retry protection. “Set stock to seven” has a different repetition property, but concurrent edits may still require a version check.
Python example
from http import HTTPStatus
def lookup(sku, products):
if sku not in products:
return HTTPStatus.NOT_FOUND, {"error": "product_not_found"}
return HTTPStatus.OK, {"sku": sku, "qty": products[sku]}
for sku in ("PEN", "BAG"):
status, body = lookup(sku, {"PEN": 3})
print(status.value, body)
Expected output
200 {'sku': 'PEN', 'qty': 3}
404 {'error': 'product_not_found'}
For the project, specify each request’s method, target, headers, body and possible responses. Choose a stable JSON error shape rather than returning a success status with a hidden error string. Do not parse a 204 body as JSON. Tests should assert status and schema together, because a correct status with a malformed representation is still a broken client contract.
Runnable Python example
Requires Python 3.10+. Save as lesson92.py and run using python or python3. The example uses local or in-memory data and makes no external network request.
from http import HTTPStatus
print(HTTPStatus.OK.value)
print(HTTPStatus.NOT_FOUND.phrase)
Expected output:
200
Not Found
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
Design HTTP responses for a product lookup API.
- Write a specification with data schema, required operations and failure conditions.
- Implement a minimal solution using small named functions.
- Add input validation and deliberate error responses.
- Test typical, boundary and invalid inputs.
- Verify the result against an independently calculated expectation.
- 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.
What is the difference between Accept and Content-Type?
Need a hint?
One header describes the representation a client is willing to receive; the other describes the body actually supplied.
Show answer and explanation
Accept is a preference for the response representation. Content-Type identifies the representation present in the current message body. They are related but not interchangeable.
Can a method be idempotent but unsafe?
Yes. PUT and DELETE change resource state, so they are unsafe, while repeating their intended operation has the same final effect as one successful request.
Must repeated DELETE calls return the same status?
No. Idempotency concerns intended state effects. A first delete may remove a resource and a second may report that it is already absent.
Should a client call json.loads on every successful response?
No. A 204 response has no content, and other successful responses may have another media type. Follow the endpoint’s status and representation contract.
Why is decrementing stock riskier to retry than setting a quantity?
A repeated decrement applies another change unless protected by an application-level idempotency mechanism. An absolute assignment has a repeatable intended effect, although concurrency still needs attention.
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.
Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.