DEV Community

Cover image for How to send an HTTP request with Python
Mobey-eth
Mobey-eth

Posted on

How to send an HTTP request with Python

Introduction

HTTP (Hypertext Transfer Protocol) is a fundamental protocol for data communication between clients and servers on the Internet. It enables the exchange of information between a client (e.g., a web browser) and a server (e.g., a web application).

What is an HTTP Request?

An HTTP request is a message that a client sends to a server over the Hypertext Transfer Protocol (HTTP). It is used to transfer all sorts of data, including HTML pages, images, videos, and JSON objects.

HTTP requests are made up of four parts:
The request method: This specifies the type of request being made. The most common request methods are GET, POST, PUT, and DELETE.

  • The request URL: This is the address of the resource that the client is requesting.
  • The request headers: This is a set of key-value pairs that contain additional information about the request. For example, the Content-Type header specifies the type of data that is being sent in the request body.
  • The request body: This is the optional body of the request, which can contain data such as form data, JSON objects, or XML documents.

Choosing the Right Library

Python offers various libraries for making HTTP requests, including httplib, urllib, and requests. In this article, we will use the "requests" library for its simplicity.

Installing the Requests Library

Before we begin, ensure you have the "requests" library installed. If not, you can easily install it running the following command on your terminal:

pip install requests

Making a GET Request with Python:
Let's put our knowledge into practice by making a GET request to a Weather API to retrieve real-time weather information.

import requests
import json
import time

# Define an API endpoint URL
URL = "http://api.weatherapi.com/v1/current.json"

# Specify the location and API key
params = {
    'q': "London",  # Location
    'key': "YOUR_API_kEY"  # Your API key
}

# Send a GET request to the API endpoint with the specified parameters in JSON format
response = requests.get(URL, params=params)

# Check if the request was successful (status code 200)
if response.status_code == 200:
    # Extract and parse the JSON response
    data = response.json()
    time.sleep(2)

    # Extract specific information from the JSON response
    location = data['location']
    city = location['name']
    country = location['country']

    current = data['current']
    temp_celsius = current['temp_c']
    condition = current['condition']['text']
    windspeed_mph = current['wind_mph']

    # Print the extracted information
    print(f"City: {city}")
    print(f"Country: {country}")
    print(f"Temperature (Celsius): {temp_celsius}°C")
    print(f"Condition: {condition}")
    print(f"Windspeed (MPH): {windspeed_mph} mph")
else:
    # Print an error message if the request failed
    print(f"Request failed with status code {response.status_code}")
Enter fullscreen mode Exit fullscreen mode

Output

Image description

Explanation of the Code

Imports:

import requests
import json
import time

Enter fullscreen mode Exit fullscreen mode

We start by importing the required libraries for this project.

Defining the API Endpoint URL and Parameters:

URL = "http://api.weatherapi.com/v1/current.json"
params = {
    'q': "London",  # Location
    'key': "YOUR_API_kEY"  # Your API key
}
Enter fullscreen mode Exit fullscreen mode

We define the URL and specify the parameters. In this case, we set the address parameter to the location we want to retrieve weather information about.

Sending a GET Request:

response = requests.get(URL, params=params)

We use the requests.get method to send a GET request to the API endpoint with the specified parameters.

Handling the Response:

if response.status_code == 200:
data = response.json()

We check if the request was successful (status code 200), and if it is, we parse the response as JSON using the response.json() method.

Extracting Specific Information from JSON Response :

location = data['location']
city = location['name']
country = location['country']
temp_celsius = data['current']['temp_c']
condition = data['current']['condition']['text']
windspeed_mph = data['current']['wind_mph']
Enter fullscreen mode Exit fullscreen mode

We extract specific information from the JSON response, such as the city, country, temperature in Celsius, condition, and windspeed in MPH.

Printing the Extracted Information:

print(f"City: {city}")
print(f"Country: {country}")
print(f"Temperature (Celsius): {temp_celsius}°C")
print(f"Condition: {condition}")
print(f"Windspeed (MPH): {windspeed_mph} mph")
Enter fullscreen mode Exit fullscreen mode

Finally, we print the extracted information to the console in an easy-to-understand format.

Conclusion

In this article, we've explored the world of HTTP requests, focusing on the GET method. We've learned how to send HTTP requests in Python using the "requests" library.

The Python Requests library makes it easy to send HTTP requests in Python. It provides a simple and easy-to-use interface for making all types of HTTP requests.

Top comments (0)