Skip to content

Module 16 · External Libraries and APIs — topic 10 of 12

HTTP requests

The HTTP protocol for programmers: methods, URLs, headers and bodies, status code classes, content types, and sending GET and POST requests with urllib — including handling error responses.

Beginner 10 min read·Lesson 244 of 306 in Python Programming

Learning objectives

  • Describe the parts of an HTTP request and response
  • Interpret status codes
  • Send GET and POST requests and handle errors with urllib

Definition

HTTP is the protocol of the web. A client sends a request (method, URL, headers and optional body) and the server returns a response (status code, headers and body).

Introduction

Every web page load, API call and form submission is an HTTP request. Knowing its parts makes debugging network code much easier.

Why it matters

Status codes and headers tell you exactly why a request failed — if you know how to read them.

Detailed explanation

Request parts: method (GET, POST, PUT, PATCH, DELETE), URL, headers (metadata such as Content-Type, Authorization, User-Agent) and an optional body.

Response parts: status code, headers and body.

Status classes: 2xx success (200 OK, 201 Created), 3xx redirection, 4xx client errors (400 Bad Request, 401 Unauthorized, 404 Not Found, 429 Too Many Requests), 5xx server errors.

GET requests should not change data and carry parameters in the URL; POST sends data in the body, usually JSON with Content-Type: application/json.

urllib.request.urlopen sends requests; a Request object sets the method, headers and body. urlopen raises HTTPError for 4xx/5xx responses — the error object still has the code and body.

Network failures (no connection, DNS problems) raise URLError; slow servers trigger a timeout if you pass timeout=.

http.HTTPStatus maps status codes to their standard phrases.

Syntax

Python
from urllib.request import Request, urlopen
import json
req = Request(url, data=json.dumps(payload).encode(),
headers={"Content-Type": "application/json"}, method="POST")
with urlopen(req, timeout=10) as resp:
print(resp.status, json.load(resp))
  • Requests have method, URL, headers, body.
  • Status codes classify outcomes.
  • HTTPError still carries the response.

Code examples

Status codes

Python
from http import HTTPStatus
for code in [200, 201, 301, 404, 429, 500]:
print(code, HTTPStatus(code).phrase)
Output
200 OK
201 Created
301 Moved Permanently
404 Not Found
429 Too Many Requests
500 Internal Server Error

Building a request

Python
from urllib.request import Request
req = Request("https://api.example.com/v1/users", data=b'{"name": "Asha"}',
headers={"Content-Type": "application/json"}, method="POST")
print(req.get_method(), req.full_url)
print(req.header_items())
Output
POST https://api.example.com/v1/users
[('Content-type', 'application/json')]

More examples

GET, POST and an error response

Python
import json
import threading
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.error import HTTPError
from urllib.parse import parse_qs, urlencode, urlparse
from urllib.request import Request, urlopen
class Echo(BaseHTTPRequestHandler):
def send_json(self, status, data):
body = json.dumps(data).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_GET(self):
url = urlparse(self.path)
if url.path == "/search":
q = parse_qs(url.query)
self.send_json(200, {"query": q["q"][0], "page": int(q.get("page", ["1"])[0])})
else:
self.send_json(404, {"error": f"no route {url.path}"})
def do_POST(self):
payload = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
self.send_json(201, {"created": payload["name"], "agent": self.headers["User-Agent"]})
def log_message(self, *args):
pass
server = HTTPServer(("127.0.0.1", 0), Echo)
threading.Thread(target=server.serve_forever, daemon=True).start()
base = f"http://127.0.0.1:{server.server_port}"
query = urlencode({"q": "python books", "page": 2})
with urlopen(f"{base}/search?{query}", timeout=5) as resp:
print(resp.status, json.load(resp))
req = Request(f"{base}/users", data=json.dumps({"name": "Asha"}).encode("utf-8"),
headers={"Content-Type": "application/json", "User-Agent": "learn-python-demo/1.0"},
method="POST")
with urlopen(req, timeout=5) as resp:
print(resp.status, json.load(resp))
try:
urlopen(f"{base}/nothing", timeout=5)
except HTTPError as e:
print(e.code, json.load(e))
server.shutdown()
Output
200 {'query': 'python books', 'page': 2}
201 {'created': 'Asha', 'agent': 'learn-python-demo/1.0'}
404 {'error': 'no route /nothing'}

Step-by-step explanation

  • The GET request carries its parameters in the encoded query string.
  • The POST request sends a JSON body with custom headers; the server reads them and replies 201 Created.
  • urlopen raises HTTPError for the 404, but the error object can still be read like a response to get the JSON error message.

Expected output

Running “GET, POST and an error response” prints exactly:

TextOutput
200 {'query': 'python books', 'page': 2}
201 {'created': 'Asha', 'agent': 'learn-python-demo/1.0'}
404 {'error': 'no route /nothing'}

Practical applications

  • Debugging failed API calls by reading status codes and error bodies.
  • Sending form data or JSON to web services.

Best practices

  • Set Content-Type for request bodies.
  • Handle HTTPError and URLError separately.
  • Always pass a timeout.

Common mistakes

Treating every non-200 as a crash

Avoid

resp = urlopen(url) # unhandled HTTPError

Prefer

try:
resp = urlopen(url, timeout=10)
except HTTPError as e:
print(e.code, e.read())

Error responses carry useful information about what went wrong.

Important notes

  • Browser developer tools (Network tab) show every HTTP request a page makes — a great way to learn.

Key takeaways

  • HTTP requests have a method, URL, headers and body.
  • Status codes: 2xx success, 4xx client error, 5xx server error.
  • urllib sends requests; HTTPError carries error responses.

Try it yourself

  1. 1
    Add a DELETE handler to the local server and send a DELETE request with urllib.
  2. 2
    Write a function that returns (status, json) for any URL, including error responses.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

Test yourself across the whole course in the Python practice bank.