Send Get and Post requests using Python

The requests library is a fantastic way to make HTTP requests from your Python scripts.  We'll go over using it for POST and GET requests. It's totally capable of PUT, DELETE, and others. But we're going to focus on just GET and POST today. Those are really the ones that we seem to use the most.

As always, we're using Python 3 in this tutorial

Let's start by installing the requests library.


pip install requests

Or if you're a Pipenv user, then go with:


pipenv install requests

Next, let's make a simple GET request to get the contents of the multiplication.com home page.


import requests

target_url = 'https://www.multiplication.com'

response = requests.get(target_url)

print(response.text)
#...HTML source of https://www.multiplication.com

At this point, I have the raw HTML content and could do some regex filtering or perhaps use a library like beautiful soup to traverse the DOM and get the info I'm looking for.

Now let's take a look at sending a POST request. For this, we'll use the placeholder service at https://jsonplaceholder.typicode.com/. This is a great service to prototype your services so you can focus on app development.


import requests

#This url will just return the post variables as JSON.
#Super helpful for testing. target_url = 'https://jsonplaceholder.typicode.com/posts' # data to be sent my_post_data = {'post_var_1':'value here', 'post_var_2':'value here', 'post_var_3':'value here', 'post_var_4':3} #Int value for example response = requests.post(url = target_url, data = my_post_data) print(response.json()) #{'post_var_1': 'value here', 'post_var_2': 'value here', 'post_var_3': 'value here', 'post_var_4': '3', 'id': 101}

For more info on the requests library, have a look at their documentation https://2.python-requests.org//en/master/. It's quite good.

Pingbacks are closed.

Comments are closed.