HTTP Requests and APIs
Understand HTTP methods, send API requests, process JSON responses, and handle network errors safely with Python.
In this lesson, you will learn
- ✓Explain HTTP requests, responses, URLs, headers, bodies, and APIs.
- ✓Distinguish GET and POST and recognize common HTTP status codes.
- ✓Build query strings safely using urllib.parse.
- ✓Send HTTP requests using urllib.request.
- ✓Decode JSON API responses and access their data.
- ✓Set timeouts and handle HTTP, URL, and JSON parsing errors.
- ✓Send JSON data in a POST request.
- ✓Apply safe API-client practices without exposing credentials or assuming every response is successful.
1. What are HTTP and APIs?
HTTP stands for Hypertext Transfer Protocol. It is a protocol used for communication between clients and servers. A client might be a Python program, browser, or mobile application. A server receives a request and returns a response.
An API, or Application Programming Interface, defines how one piece of software interacts with another. A web API commonly exposes resources or operations through HTTP endpoints.
An endpoint is a URL used to access a particular resource or operation. For example, an API might expose /products to list products and /products/42 to retrieve a particular product. The exact behavior depends on the API's documentation.
A request can include a method, URL, headers, and sometimes a body. A response can include a status code, headers, and a body. The body may contain JSON, text, binary data, or no content.
The request-response cycle
The Python program sends a request to the server. The server processes the request according to its API rules. The response includes a status code and may include a body. The Python program checks the response and processes the body.
Note
2. Understand URLs, query parameters, and headers
A URL identifies a resource. A typical HTTPS URL contains a scheme, host, path, and optional query string. A fragment, when present, is generally interpreted by the client and is not sent as part of the HTTP request target.
Query parameters are commonly used to filter, search, sort, or paginate results. For example, /products?category=books&page=2 includes category and page parameters.
Do not construct query strings by concatenating arbitrary user input. Use urllib.parse.urlencode() to encode parameter names and values correctly.
Headers carry metadata. An Accept header can indicate the response formats a client prefers. A Content-Type header describes the format of a request or response body. APIs may also define headers for authentication, rate limits, caching, and other behavior.
Build a query string safely
urlencode() converts the dictionary into URL-encoded query parameters. The space in python basics is encoded as + under the standard form-style encoding used by urlencode(). The integer 1 is represented as the text 1. The resulting string can be appended to a URL after a question mark.
3. Common HTTP methods
The HTTP method describes the intended operation. GET is commonly used to retrieve a resource. POST submits data for processing and often creates a resource or causes another server-side effect.
PUT is commonly used to create or replace a resource at a known URL, while PATCH applies a partial modification. DELETE requests removal of a resource. The precise semantics depend on HTTP and the API's contract.
GET requests should be used for retrieval rather than actions that change server state. A GET request can still be logged or counted by a server, but it is not intended to modify the requested resource.
POST requests can have side effects. Sending the same POST twice may create two records or submit an action twice, so do not automatically retry non-idempotent operations without understanding the API's guarantees.
Common methods at a glance
These are common uses, not a guarantee that every endpoint supports every method. The API documentation determines which methods are supported for each endpoint. A server may reject a method with a status such as 405 Method Not Allowed.
4. Understand HTTP status codes
A response status code communicates the broad outcome of a request. Status codes are grouped into five classes: 1xx informational, 2xx successful, 3xx redirection, 4xx client errors, and 5xx server errors.
200 OK commonly indicates success. 201 Created indicates that a resource was created. 204 No Content indicates success with no response content. 400 Bad Request indicates a problem with the request, while 401 Unauthorized usually means authentication is required or invalid. 403 Forbidden indicates that the server refuses the operation, and 404 Not Found indicates that the requested resource was not found.
429 Too Many Requests indicates rate limiting. 500 Internal Server Error and 503 Service Unavailable are examples of server-side failures.
A response with a successful HTTP status can still contain unexpected or invalid application data. Check both the status and the response body.
Status-code reference
The number communicates the status class and specific outcome. A 2xx status indicates success at the HTTP level, but the meaning of success depends on the method and endpoint. A 4xx status generally points to a request or permission issue. A 5xx status generally points to a server-side problem.
Note
5. Make a real GET request with urllib
Python's standard library includes urllib.request for opening URLs and sending HTTP requests. This means the basic examples do not require installing requests or another third-party HTTP client.
urlopen() can open a URL and return a response object. Use a with statement to manage the response, inspect its status, and read its body. The timeout argument limits how long the operation waits for a response or network activity; it is not a guarantee that every multi-step request will finish within one exact total duration.
The following example requests a public test endpoint. It requires an internet connection and the endpoint to be reachable. Its live response can change, so the lesson does not promise a fixed response body.
Send a GET request
This is an illustrative successful response from the public test endpoint; network availability and response headers can vary. urlopen() sends the request and returns a response object if the request succeeds. response.status provides the HTTP status code. response.headers exposes response headers. response.read() returns the body as bytes, and len(body) > 0 checks whether the response contains data.
Caution
6. Decode a JSON API response
Many APIs return JSON. A response body is initially bytes when read from an HTTP response. Decode it into text using the appropriate encoding, then parse it with json.loads(), or parse the bytes directly with json.loads().
The response body must actually contain valid JSON. Some endpoints return HTML error pages, plain text, or an empty body, even when a program expects JSON.
The next example demonstrates JSON parsing locally with a fixed string. It can be run without an internet connection and has a deterministic output.
Parse a JSON response body
The b prefix creates a bytes object containing UTF-8-compatible JSON text. json.loads() accepts bytes as well as strings containing valid JSON. The result is a Python dictionary. The score is a Python integer, so it can be used in arithmetic without an additional conversion.
7. Send JSON with a POST request
A POST request can send data in its request body. For a JSON API, serialize a Python dictionary with json.dumps(), encode the resulting string as UTF-8 bytes, and set Content-Type to application/json.
A request may include Accept: application/json to indicate the response format the client prefers. These headers have different purposes: Content-Type describes the request body, while Accept describes acceptable response formats.
Only send data to an endpoint that you are authorized to use. Even a test API can log request data, and a POST operation may cause a server-side effect.
Prepare and send JSON data
json.dumps() serializes the dictionary into JSON text. encode('utf-8') converts the text into bytes for the request body. The Content-Type header identifies the body as JSON. Request specifies the POST method and body. httpbin.org/post is a public testing endpoint that echoes submitted request data. The output assumes the endpoint is reachable and returns its usual response structure.
Caution
8. Handle HTTP and network errors
Network requests can fail for many reasons. The server might return an error status, the host might not resolve, the connection might fail, or the request might exceed its timeout.
urllib.error.HTTPError is raised for HTTP error responses such as 404 or 500 by urllib's default handler. HTTPError is also a subclass of URLError, so catch HTTPError first when you need to distinguish HTTP status failures from other URL-related failures.
URLError covers other URL-access problems, including many connection failures. Timeout-related failures can surface through the URL error hierarchy or as timeout exceptions depending on where the failure occurs.
A remote server can return a successful HTTP response containing invalid JSON. Handle JSONDecodeError separately if your application expects JSON.
Use targeted exception handling. Avoid retrying indefinitely or automatically repeating a POST request when the server might already have processed it.
Handle HTTP and URL errors
This is a template for handling failures, not a promise of a particular result from example.com. If the server returns an HTTP error such as 404, HTTPError can provide the status code. If the host cannot be reached or another URL-related problem occurs, URLError may be raised. The actual result depends on the requested resource and current network conditions.
Note
9. Build a small reusable API function
Reusable functions keep networking logic in one place. Instead of repeating request construction, timeout settings, and JSON parsing throughout a program, create a function with a clear purpose and return parsed data to the caller.
A function should not assume that every API response has the same shape. Validate required fields before using them, and let the caller decide how to present or store the result.
This example shows a small function that makes a GET request and returns decoded JSON. It can be adapted for an API whose documented response is JSON.
Create a JSON API helper
get_json() accepts a URL and builds a request with an Accept header. urlopen() uses a finite timeout rather than waiting without a limit. The with block ensures the response is closed. The function returns parsed Python data rather than printing it. The final two lines are commented out so the function can be defined and inspected without making a network request.
Note
10. Security and reliability practices
Use HTTPS when communicating with services that support it. HTTPS protects data in transit between the client and the server when certificate validation succeeds, but it does not make a service trustworthy or validate the data it returns.
Do not hard-code API keys or passwords into source files, commit them to version control, or print them in logs. Use environment variables or a suitable secret-management system when credentials are required.
Use a finite timeout so a stalled network operation does not wait indefinitely. Respect API rate limits, and follow the service's documentation for pagination, authentication, and retries.
Validate response data before relying on it. For example, check that a field exists and has the expected type before converting it or accessing nested keys.
Avoid sending confidential data to public demo endpoints. Do not make requests to services or endpoints you are not authorized to use.
Treat URLs and responses as untrusted input. If an application accepts user-supplied URLs, consider server-side request forgery risks and restrict destinations appropriately rather than allowing arbitrary internal or private-network access.
Validate a required field
The example uses a local Python dictionary so its output is deterministic. The first check verifies that data is a dictionary. The following checks validate the types of two required fields. The example demonstrates basic shape validation; real applications may need additional constraints, such as rejecting booleans where a strict integer is required.
Caution
Common pitfalls to avoid
Real debugging lessons and exact syntax contrasts to avoid runtime bugs
#1 Assuming every HTTP response indicates success.
Why it happens: HTTP responses include error status codes as well as successful ones; inspect the status and handle HTTPError or other failure cases.
Key takeaway: Inspect the response status and handle HTTP errors before relying on the response body.
#2 Building query strings by manually concatenating unescaped user input.
Why it happens: Manually concatenated query strings can break on spaces and special characters; use URL encoding utilities to encode parameters safely.
Key takeaway: Use urllib.parse.urlencode() for query parameters.
#3 Assuming a response body is always valid JSON.
Why it happens: A server may return HTML, an empty body, or malformed JSON, so handle decoding errors separately from network and HTTP errors.
Key takeaway: Parse the body deliberately and handle json.JSONDecodeError when JSON is expected.
#4 Sending a Python dictionary directly as a JSON request body.
Why it happens: A Python dictionary is not JSON text by itself; serialize the payload with json.dumps() and set the appropriate content type when sending JSON.
Key takeaway: Serialize the dictionary with json.dumps(), encode the text to bytes, and set Content-Type to application/json.
#5 Making requests without a timeout.
Why it happens: Without a timeout, a network call can wait much longer than expected; set a reasonable timeout and handle timeout errors.
Key takeaway: Set an appropriate finite timeout and handle the possible failures.
#6 Catching URLError before HTTPError when trying to distinguish them.
Why it happens: HTTPError is a specialized URLError, so catch it first when the program needs to distinguish HTTP status failures from other URL/network failures.
Key takeaway: Catch HTTPError first because it is a subclass of URLError.
#7 Automatically retrying every failed request.
Why it happens: Retries can duplicate actions or worsen outages, especially for non-idempotent requests; retry only suitable failures with limits and backoff.
Key takeaway: Use a deliberate retry policy, especially for POST requests that may cause side effects.
#8 Hard-coding API credentials in source code.
Why it happens: Hard-coded API keys can leak through source control and logs; load secrets from secure configuration and rotate any exposed credentials.
Key takeaway: Keep credentials out of version control and use environment variables or a secret manager.
Ready for hands-on challenges?
Test your skills with shuffled coding challenges in the Practice Arena.
Technical and placement interview questions
Frequently tested interview questions with detailed, full answers (click to expand)
Q1:What is HTTP?
Q2:What is an API endpoint?
Q3:What is the difference between GET and POST?
Q4:What is the difference between Content-Type and Accept?
Q5:How do you send an HTTP request using Python's standard library?
Q6:How do you parse JSON returned by an API?
Q7:What is the difference between HTTPError and URLError?
Q8:Why should API requests use a timeout?
Q9:Why should a client inspect the status code before processing a response?
Q10:What are important practices when building an API client?
Key takeaways
- An API defines how software interacts with a service; HTTP is a common protocol used for web APIs.
- A request can include a method, URL, headers, and body. A response includes a status code, headers, and sometimes a body.
- GET commonly retrieves data, while POST submits data and may cause side effects.
- Use urlencode() to construct query strings correctly.
- Use urllib.request to send HTTP requests with Python's standard library.
- Use json.loads() to parse a valid JSON response body.
- Inspect status codes and validate response data instead of assuming every response is successful.
- Use finite timeouts and handle HTTPError, URLError, timeout-related failures, and JSONDecodeError appropriately.
- Protect credentials, use HTTPS where available, respect rate limits, and retry only when the operation's behavior makes retrying appropriate.
Related Topics & Next Steps
4 Recommended LessonsStrengthen your Python foundation with these complementary core lessons: