HTTP Basics & urllib
HTTP (HyperText Transfer Protocol) is the foundation of data communication on the web. Python's standard library includes urllib for making HTTP requests without any third-party dependencies.
HTTP Methods
Each HTTP request uses a method (also called a verb) that describes the intended action:
| Method | Purpose | Has Body? |
|---|---|---|
| GET | Retrieve a resource | No |
| POST | Create a new resource | Yes |
| PUT | Replace a resource entirely | Yes |
| PATCH | Partially update a resource | Yes |
| DELETE | Delete a resource | No |
REST APIs follow these conventions:
GET /usersโ list all usersPOST /usersโ create a new userGET /users/42โ get user 42PUT /users/42โ replace user 42PATCH /users/42โ update specific fields of user 42DELETE /users/42โ delete user 42
HTTP Status Codes
The server always responds with a status code indicating success or failure:
2xx โ Success
200 OKโ request succeeded, body contains the result201 Createdโ resource was successfully created (often after POST)204 No Contentโ succeeded but no body (often after DELETE)
3xx โ Redirection
301 Moved Permanentlyโ resource has a new permanent URL302 Foundโ temporary redirect
4xx โ Client Errors (your fault)
400 Bad Requestโ malformed request syntax or invalid parameters401 Unauthorizedโ authentication required or failed403 Forbiddenโ authenticated but not permitted404 Not Foundโ resource doesn't exist422 Unprocessable Entityโ valid syntax but semantic errors in body429 Too Many Requestsโ rate limit exceeded
5xx โ Server Errors (server's fault)
500 Internal Server Errorโ unexpected server-side crash502 Bad Gatewayโ upstream server failure503 Service Unavailableโ server overloaded or in maintenance
Making a Simple GET Request
urllib.request.urlopen opens a URL and returns a response object:
The response object implements a context manager โ always use with to ensure the connection is closed.
Reading JSON Responses
Most modern APIs return JSON. Use the json module to parse it:
Building Query Parameters with urllib.parse
Never manually concatenate query strings โ use urllib.parse.urlencode:
Use urllib.parse.quote to percent-encode a single string value (e.g., a search term with spaces or special characters):
Custom Headers with urllib.request.Request
Use urllib.request.Request to add custom headers, change the method, or add a request body:
POST Requests with a JSON Body
Error Handling
urllib.error.HTTPError is raised for 4xx and 5xx responses. urllib.error.URLError is raised for network-level failures (DNS, connection refused, timeout):
Setting Timeouts
Prevent your program from hanging indefinitely by always specifying a timeout:
A Complete Example
Knowledge Check
Which HTTP status code indicates that a resource was successfully created by a POST request?
What is the correct way to build query parameters for a URL in Python's standard library?
What exception does urllib raise when the server responds with a 404 status code?