Blog

Python GET and POST Requests

  • (4.0)
  • | 2468 Ratings |
  • Last Updated September 01, 2017

On any given day, if you would want to interact with any other programming language or a RESTful API that has been provided by a third party, we would be relying on the HTTP protocol’s GET and POST methods in general. Alongside that, we would also take a look at how these two methods are implemented within the Python’s context. So, even before we start getting into further details, let us take a moment and understand what HTTP actually means and what is it that you as a Python programmer should be concentrating on.

So what is HTTP?

1. HTTP is acronym that stands for Hypertext Transfer Protocol
2. To lay forward its complete sense of meaning, it is a set of protocols designed to enable communication between clients and servers.

With this basic understanding of HTTP as such, let us gain some knowledge into the methods that are provided by this protocol and we shall limit our boundaries to just 2 methods for the request / response cycles from your server (namely):

1. GET
2. POST

Python provides different API’s or libraries for us to leverage on using these to communicate with servers. Servers in this case can be an API, or a service provided by another application, or an application in itself. Let us take a look at the HTTP libraries provided for Python programmers to use the GET and POST methods in Python:

httplib
urllib
requests

One of the best ways to interact with Python using the GET and POST requests is to use ‘requests’

Let us look at an example using the requests library to make the necessary GET and POST requests, and in the process let us make ourselves familiarized with the syntax and the like.

Learn how to use Python, from beginner basics to advanced techniques, with online video tutorials taught by industry experts. Enroll for Free Python Training Demo!

GET Request:

Let us leverage on the Google Map APIs to read / write data on to Google Maps. Using the Google Map APIs let us read some information about a location and display it on the console for the users to gain on the information produced. We will then understand the syntax and the usage to make ourselves acquainted to it. Generally, the data is provided in JSON format. (JSON- JavaScript Object Notation). This is implemented as dictionary objects in Python.

import requests

URL = "https://maps.googleapis.com/maps/api/geocode/json"
location = "Osmania University"
PARAMS = {'address':location}

response = requests.get(url = URL, params = PARAMS)
data = response.json()

latitude = data['results'][0]['geometry']['location']['lat']
longitude = data['results'][0]['geometry']['location']['lng']
formattedAddress = data['results'][0]['formatted_address']

print("Latitude : %snLongitude : %snAddress of the location : %s"
    %(latitude, longitude,formattedAddress))

Output:

Latitude : 17.413502
Longitude : 78.5287355
Address of the location : Osmania University Main Rd, Amberpet, Hyderabad, Telangana 500007, India

Frequently Asked Python Interview Questions & Answers

Now to understand what has happened in the program shown above, the parameters ‘URL’ and ‘PARAMS’ are passed to the GET method to hit the Google Maps API and retrieve the address and latitude / longitude details of the input location provided. Note that the get() method is invoked using the requests module from Python. Isn’t that easy?

Related Page: Defining Functions - Python

Important points to note here in making a GET request:

The URL for a GET request carries the necessary parameters with it. For requests, parameters can be defined as a dictionary which will later be parsed and added to the base url or the endpoint.
Once the URL is generated with the parameters appended to the base url or the endpoint, we then invoke the get() method of the requests module of Python.
This in turn returns a response object which contains the actual response related details that we need to retrieve as a JSON (JavaScript Object Notation).

Now if you are planning to use your own API’s then it is a stressful task of building your own RESTful API and then test whether Python GET works or not, instead relying on third party API for testing is very well sufficient. Now, let us take an example of using a similar request with a POST request using requests module of Python.

import requests

payload = (('key1', 'value1'), ('key1', 'value2'))
r = requests.post('https://httpbin.org/post', data=payload)
print(r.text)

Output:
{
    "args": {},
    "data": "",
    "files": {},
    "form": {
        "key1": [
            "value1",
            "value2"
        ]
    },
    "headers": {
        "Accept": "*/*",
        "Accept-Encoding": "gzip, deflate",
        "Connection": "close",
        "Content-Length": "23",
        "Content-Type": "application/x-www-form-urlencoded",
        "Host": "httpbin.org",
        "User-Agent": "python-requests/2.9.1"
    },
    "json": null,
    "origin": "XX.XX.XX.XXX",
    "url": "https://httpbin.org/post"
}

Observe the difference in the way the post() method is invoked. The requests module is used to invoke the post() method, providing the necessary details that it ought to send to complete a POST request to the server / API (as in this case).

Related Page: Python Operators

Important points to note here in making a POST request:

The URL for a POST request carries the necessary parameters with it. Parameters will later be parsed and added to the base url or the endpoint.
Once the URL is generated with the parameters appended to the base url or the endpoint, we then invoke the post() method of the requests module of Python.
This in turn returns a response object which contains the actual response related details that we need to retrieve as a JSON (JavaScript Object Notation).

In this article, we have tried to introduce the concept of using HTTP methods GET and POST within the context of Python. We have then tried out a couple of examples on how to invoke a GET request and a POST request on two different APIs to check how it exactly works.

Explore Python Sample Resumes! Download & Edit, Get Noticed by Top Employers!Download Now!

 

Subscribe For Free Demo

Free Demo for Corporate & Online Trainings.

Free Demo Popup -->