GET, POST, PUT, Delete Requests in Python

In this part of Learning Python we Cover GET, POST, PUT, Delete Requests in python
Written by Paayi Tech |10-May-2019 | 0 Comments | 365 Views

As we have already studied what is HTTP requests and how it works in the networking section. In this section, we will learn how to make HTTP requests from python without using servers and browsers. Generally, if we want to see anything we go to our browser and give the link in a URL section. After making the HTTP request, it shows on our main page. However, similar things can be done from the python.

However, why there is a need to make an HTTP request from python? Sometimes we need the data from the websites. We can get that data either by using API’s or by scraping that data if API is not available to retrieve that data. The scraping of data is called web scraping.

 

To make a request we first have to install the python request module by the pip command as follows:

Windows:

pip install requests

 

Linux or Mac

pip3 install requests

 

After a successful installation we are good to go:

Types of Requests:

There are four types of requests. The requests are as follows:

  • GET requests
  • POST requests
  • PUT requests
  • DELETE requests

 

Get requests is used to get the content. It can be an HTML or JSON. Post request is used to post the data. We can send additional parameters with it to add the data. Put requests are used to update the already existing data. Moreover, delete request delete the data from the API endpoints.

 

Get Request:

The syntax of using the get request is as follows:

import requests
 
response = requests.get('https://www.google.com')

 

Post Request:

The syntax of using the get request is as follows:

import requests
 
response = requests.post('https://www.api./post_data')

 

Similar syntax is for putting the data and deleting the data.

Passing value as a Parameter:

In Google, we often see when we enter the search query, and press enters the URL changes from google.com to googl.com?q=QueryString. That q variable is a parameter. Sometimes the endpoint requires the additional parameter to be entered. Requests module provides us these arguments as a dictionary of string using these parameters as key-value pair the objective can be achieved.

Following is the example of sending additional parameters which are called payload.

import requests
 
payload = {'username':'name','password':'123456'}
r = requests.get('https://dummpyapi.com/get', params=payload)

 

Now if we get the URL from the r variable we will get the following URL:

https://dummpyapi.com/get?username=name&password=123456

 

Response content:

There are mostly two types of response we usually get. One is a JSON response. This response is generated when we are trying to call the API. API’s are mostly in the JSON format and return the response as a JSON format. For those who don’t know what JSON response. JSON stands for JavaScript Object Notation. It is similar to the dictionary in python. The other response we get is an HTML response. This response is generated when we try to requests the HTML website. We do this when we try to scrape the data from that website when we don’t have access to the data or an API.

  • Response 200: This response is generated when the get requests are successful. This code indicates the requests are made and the data is fetched
  • Response 201: This response is generated when the post request successfully posted the data into the database.
  • Response 400: This indicates terrible requests. This means either the URL is not correct or parameters that are required are not sent.
  • Response 403: This means that the user is not authorized to access the data from that particular websites. Either username or password is not given, or the auth token is incorrect.
  • Response 500:  This means that there is an internal server error. It is generated when there is some problem with the code.

 

How to get the Status Code:

After sending the requests, we can see our request is successful, or there is an error. To know the status code following implementation can be done:

import requests
 
payload = {'username':'name','password':'123456'}
r = requests.get('https://dummpyapi.com/get', params=payload)
print(r.status_code)

 

TimeOut:

We can tell the request function to stop waiting for the response after a certain interval of time. The method that is used for this purpose is by giving the additional argument in the request function. The parameter is a timeout. If the request runs out of time the requests function raise an exception. Following is the code to do so:

import requests
 
r = requests.get('https://www.google.com',timeout=0.0001)

The output of the following code is the error which is as follows:

raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='www.google.com', port=443): Max retries exceeded with url: / (Caused by NewConnectionError(': Failed to establish a new connection: [Errno 101] Network is unreachable',))

 

As we have set the timeout so low that it is unable to fetch the data in that time. It is unable to fetch the data in that short time, and it will generate an error of failing to establish the connection in time.

 

Headers:

The header is extra information that is attached to the requests. Sometimes the URL required headers like what sort of response you needed in return and what is the type of payload are the user sending. What is the authentication URL to access this website all this and more are defined in a header? If we don’t pass the parameters in the header, it will generate an error in response.

So how to send the headers? It is straightforward sending header in python. If anyone used android, it is a quite complicated procedure to send the header. However, in python, it is a piece of cake. It is just like sending the parameters as we have seen in the above example. Following is the example of sending the header in python requests module:

import requests
 
header = {'Content-Type': 'application.json'
          'auth_toke': '7126769736976497265764tydgsyugfst86w25r654'
          }
 
r = requests.get('https://www.dummpyapi.com/post', headers=header)

 

If we are sending the requests to like google API’s which strictly required the auth tokens and content type so we can assign it in this way.

In the next section, we will request a dummy data.





Login/Sign Up

Comments




Related Posts



© Copyright 2019, All Rights Reserved. paayi.com

This site uses cookies. By continuing to use this site or clicking "I Agree", you agree to the use of cookies. Read our cookies policy and privacy statement for more information.