Http Client in Logo
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://pythonexample.com")
# Check if the request was successful
response.raise_for_status()
# 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 use the requests library to create a simple HTTP client. Here’s a breakdown of the code:
We import the
requestslibrary, which provides a user-friendly interface for making HTTP requests.In the
main()function, we userequests.get()to send a GET request to “https://pythonexample.com”. This method returns aResponseobject.We call
response.raise_for_status()to raise an exception for any unsuccessful HTTP status codes (4xx or 5xx).We print the response status using
response.status_codeandresponse.reason.To print the first 5 lines of the response body, we split the response text into lines and iterate over the first 5 using a slice.
The
if __name__ == "__main__":block ensures thatmain()is only called if the script is run directly, not if it’s 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 code in a file named
http_client.py.Run the script from the command line:
python http_client.py
This example demonstrates how to make HTTP requests in Python, handle responses, and process the response data. The requests library abstracts away many of the complexities of working with HTTP, making it easier to work with web services and APIs in Python.