Http Client in Python
Here’s an idiomatic Python example demonstrating how to create an HTTP client:
import requests
def main():
# Send an HTTP GET request to a server
response = requests.get("https://www.example.com")
# Print the HTTP response status
print(f"Response status: {response.status_code} {response.reason}")
# Print the first 5 lines of the response body
lines = response.text.splitlines()
for line in lines[:5]:
print(line)
if __name__ == "__main__":
main()This Python script demonstrates how to create a simple HTTP client using the requests library, which is a popular and user-friendly way to make HTTP requests in Python.
Let’s break down the code:
We import the
requestslibrary, which provides a convenient API for making HTTP requests.In the
main()function, we userequests.get()to send a GET request to “https://www.example.com”. This method returns aResponseobject.We print the response status using
response.status_codeandresponse.reason, which give us the numeric status code and the corresponding reason phrase.To print the first 5 lines of the response body, we split the response text into lines using
response.text.splitlines(), then iterate over the first 5 lines using slicing ([:5]).The
if __name__ == "__main__":block ensures that themain()function is only called if the script is run directly (not imported as a module).
To run this script:
Make sure you have the
requestslibrary installed. You can install it using pip:pip install requestsSave the script in a file, e.g.,
http_client.py.Run the script from the command line:
python http_client.py
This will output the response status and the first 5 lines of the response body.
This example demonstrates how Python’s requests library simplifies HTTP client operations compared to using lower-level libraries. It handles connection pooling, SSL verification, and many other details automatically, making it an excellent choice for most HTTP client needs in Python.