Python GET and POST Requests

On any given day, if you would like 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. Apart that, Let us take a look at how these two methods are implemented within the Python’s context. So, 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.

If you want to Enrich your career with a Python certified professional, then visit Mindmajix - A Global online training platform:  Python Certification Course.  This course will help you to achieve excellence in this domain.

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.

 MindMajix YouTube Channel

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 let us understand what 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 for 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 post() method is invoked. The requests module is used to invoke the post() method, providing necessary details that it ought to send to complete a POST request to the server / API (as in this case).

[Related PagePython Operators

Post Request

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.

If you are interested to learn Python and to become an Python Expert? Then check out our Python Certification Training Course at your near Cities.

Python Course ChennaiPython Course BangalorePython Course DallasPython Course Newyork

These courses are incorporated with Live instructor-led training, Industry Use cases, and hands-on live projects. This training program will make you an expert in Python and help you to achieve your dream job.

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

 

Job Support Program

Online Work Support for your on-job roles.

jobservice

Our work-support plans provide precise options as per your project tasks. Whether you are a newbie or an experienced professional seeking assistance in completing project tasks, we are here with the following plans to meet your custom needs:

  • Pay Per Hour
  • Pay Per Week
  • Monthly
Learn MoreGet Job Support
Course Schedule
NameDates
Python TrainingNov 19 to Dec 04View Details
Python TrainingNov 23 to Dec 08View Details
Python TrainingNov 26 to Dec 11View Details
Python TrainingNov 30 to Dec 15View Details
Last updated: 03 Apr 2023
About Author

Anjaneyulu Naini is working as a Content contributor for Mindmajix. He has a great understanding of today’s technology and statistical analysis environment, which includes key aspects such as analysis of variance and software,. He is well aware of various technologies such as Python, Artificial Intelligence, Oracle, Business Intelligence, Altrex, etc. Connect with him on LinkedIn and Twitter.

read less
  1. Share:
Python Articles