How to make a get request Python

"Learn how to make a get request in Python with an example code snippet."

Making a GET Request with Python

Making a GET request with Python is quite simple. We can use the requests library to make a GET request. This library is available to install with the pip command.

pip install requests

Once the library has been installed, it can be imported into a Python file. For example:

import requests

Now that the library has been imported, we can make a GET request to a URL. This can be done with the requests.get() method. For example:

r = requests.get("http://www.example.com")

The r variable now contains the response of the GET request. We can access the response data in a variety of ways. For example, we can access the response text with the .text attribute:

print(r.text)

We can also access the response headers with the .headers attribute:

print(r.headers)

We can also access the response status code with the .status_code attribute:

print(r.status_code)

We can also pass parameters to the request with the params argument. This argument takes a dictionary of parameters as its value:

params = {'key1': 'value1', 'key2': 'value2'}
r = requests.get("http://www.example.com", params=params)

And that's it! Making a GET request with Python is straightforward using the requests library.

Answers (0)