The Wayback Machine - https://web.archive.org/web/20241003043121/https://www.geeksforgeeks.org/python-requests-tutorial/
Open In App

Python Requests Tutorial

Last Updated : 24 Nov, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The Requests library in Python is one of the integral parts of Python for making HTTP requests to a specified URL. Whether it be REST APIs or Web Scraping, requests are a must to be learned for proceeding further with these technologies. When one makes a request to a URI, it returns a response. Python requests provide inbuilt functionalities for managing both the request and response.

In this tutorial, we will explore What is Python Request Library, How to make GET requests through Python Requests, Response objects and Methods, Authentication using Python Requests, and so on.

python-requests-module

What is Python Requests module?

  • Requests is an Apache2 Licensed HTTP library, that allows to send HTTP/1.1 requests using Python.
  • To play with web, Python Requests is must. Whether it be hitting APIs, downloading entire facebook pages, and much more cool stuff, one will have to make a request to the URL.
  • Requests play a major role is dealing with REST APIs, and Web Scraping.
  • Checkout an Example Python Script using Requests and Web Scraping – Implementing Web Scraping in Python with BeautifulSoup

Installing Requests

Requests installation depends on type of operating system on eis using, the basic command anywhere would be to open a command terminal and run,

pip install requests

The basic method for installation of requests on any operating system is to grab the base files and install requests manually and Requests is actively developed on GitHub, where the code is always available. For code – visit here. You can either clone the public repository:

git clone git://github.com/psf/requests.git

Once you have a copy of the source, you can embed it in your own Python package, or install it into your site-packages easily:

cd requestspip install .

For more checkout – How to install requests in Python – For windows, linux, mac

Making a Request

Python requests module has several built-in methods to make Http requests to specified URI using GET, POST, PUT, PATCH or HEAD requests. A Http request is meant to either retrieve data from a specified URI or to push data to a server. It works as a request-response protocol between a client and a server. Let’s demonstrate how to make a GET request to an endpoint. GET method is used to retrieve information from the given server using a given URI. The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ‘?’ character. For example:

https://www.google.com/search?q=hello

How to make GET request through Python Requests

Python’s requests module provides in-built method called get() for making a GET request to a specified URI.

Syntax

requests.get(url, params={key: value}, args)

Example :

Let’s try making a request to github’s APIs for example purposes.

Python3




import requests
   
# Making a GET request
  
# check status code for response received
# success code - 200
print(r)
  
# print content of request
print(r.content)


save this file as request.py and through terminal run,

python request.py

Output –

python-requests-get-method

For more, visit – GET method – Python requests

Http Request Methods

Method Description
GET GET method is used to retrieve information from the given server using a given URI.
POST POST request method requests that a web server accepts the data enclosed in the body of the request message, most likely for storing it
PUT The PUT method requests that the enclosed entity be stored under the supplied URI. If the URI refers to an already existing resource, it is modified and if the URI does not point to an existing resource, then the server can create the resource with that URI.
DELETE The DELETE method deletes the specified resource
HEAD The HEAD method asks for a response identical to that of a GET request, but without the response body.
PATCH It is used for modify capabilities. The PATCH request only needs to contain the changes to the resource, not the complete resource

Response object

When one makes a request to a URI, it returns a response. This Response object in terms of python is returned by requests.method(), method being – get, post, put, etc. Response is a powerful object with lots of functions and attributes that assist in normalizing data or creating ideal portions of code. For example, response.status_code returns the status code from the headers itself, and one can check if the request was processed successfully or not. Response object can be used to imply lots of features, methods, and functionalities.

Example :

Python3




# import requests module
import requests
# Making a get request
response = requests.get('https://api.github.com/')
# print request object
print(response.url)
# print status code
print(response.status_code)


Save this file as request.py, and run using below command

Python request.py

response-python-requests

Status code 200 indicates that request was made successfully.

Response Methods

Method Description
response.headers response.headers returns a dictionary of response headers.
response.encoding response.encoding returns the encoding used to decode response.content.
response.elapsed response.elapsed returns a timedelta object with the time elapsed from sending the request to the arrival of the response.
response.close() response.close() closes the connection to the server.
response.content response.content returns the content of the response, in bytes.
response.cookies response.cookies returns a CookieJar object with the cookies sent back from the server.
response.history response.history returns a list of response objects holding the history of request (url).
response.is_permanent_redirect response.is_permanent_redirect returns True if the response is the permanent redirected url, otherwise False.
response.is_redirect response.is_redirect returns True if the response was redirected, otherwise False.
response.iter_content() response.iter_content() iterates over the response.content.
response.json() response.json() returns a JSON object of the result (if the result was written in JSON format, if not it raises an error).
response.url response.url returns the URL of the response.
response.text response.text returns the content of the response, in unicode.
response.status_code response.status_code returns a number that indicates the status (200 is OK, 404 is Not Found).
response.request response.request returns the request object that requested this response.
response.reason response.reason returns a text corresponding to the status code.
response.raise_for_status() response.raise_for_status() returns an HTTPError object if an error has occurred during the process.
response.ok response.ok returns True if status_code is less than 200, otherwise False.
response.links response.links returns the header links.

Authentication using Python Requests

Authentication refers to giving a user permissions to access a particular resource. Since, everyone can’t be allowed to access data from every URL, one would require authentication primarily. To achieve this authentication, typically one provides authentication data through Authorization header or a custom header defined by server.

Example –

Python3




# import requests module
import requests
from requests.auth import HTTPBasicAuth
# Making a get request
response = requests.get('https://api.github.com / user, ',
            auth = HTTPBasicAuth('user', 'pass'))
# print request object
print(response)


Replace “user” and “pass” with your username and password. It will authenticate the request and return a response 200 or else it will return error 403.

authenticate-python-requests

For more visit – Authentication using Python requests

SSL Certificate Verification

Requests verifies SSL certificates for HTTPS requests, just like a web browser. SSL Certificates are small data files that digitally bind a cryptographic key to an organization’s details. Often, an website with a SSL certificate is termed as secure website. By default, SSL verification is enabled, and Requests will throw a SSLError if it’s unable to verify the certificate.

Disable SSL certificate verification

Let us try to access a website with an invalid SSL certificate, using Python requests

Python3




# import requests module
import requests
# Making a get request
response = requests.get('https://expired.badssl.com/')
# print request object
print(response)


Output :-

ssl-certificate-verification-python-requests

This website doesn’t have SSL setup so it raises this error. one can also pass the link to the certificate for validation via python requests only.

Python3




# import requests module
import requests
# Making a get request
response = requests.get('https://github.com', verify ='/path/to/certfile')
# print request object
print(response)


This would work in case the path provided is correct for SSL certificate for github.com.

For more visit- SSL Certificate Verification – Python requests

Session Objects

Session object allows one to persist certain parameters across requests. It also persists cookies across all requests made from the Session instance and will use urllib3’s connection pooling. So if several requests are being made to the same host, the underlying TCP connection will be reused, which can result in a significant performance increase. A session object all the methods as of requests.

Using Session Objects

Let us illustrate use of session objects by setting a cookie to a url and then making a request again to check if cookie is set.

Python3




# import requests module
import requests
  
# create a session object
s = requests.Session()
  
# make a get request
  
# again make a get request
  
# check if cookie is still set
print(r.text)


Output:

session-objects-python-requests

For more, visit – Session Objects – Python requests

Conclusion

Python Request Library is a powerful tool for making HTTP requests and interacting with web APIs. In this tutorial, we covered the basics of sending GET and POST requests, handling parameters and headers, and managing response data. The library’s simplicity and intuitive design make it accessible for both beginners and experienced developers.



Similar Reads

GET and POST Requests in GraphQL API using Python requests
In this article, we will be understanding how to write GET and POST requests to GRAPHQL APIs using the Python request module. Dealing with GraphQL API is a bit different compared to the simple REST APIs. We have to parse in a query that involves parsing the GraphQL queries in the request body. What are Requests in Python Requests is a python packag
9 min read
HEAD method - Python requests
Requests library is one of the important aspects of Python for making HTTP requests to a specified URL. This article revolves around how one can make HEAD request to a specified URL using requests.head() method. Before checking out the HEAD method, let's figure out what a Http HEAD request is - HEAD Http Method HEAD is a request method supported by
2 min read
DELETE method- Python requests
Requests library is one of the important aspects of Python for making HTTP requests to a specified URL. This article revolves around how one can make DELETE request to a specified URL using requests.delete() method. Before checking out the DELETE method, let's figure out what a Http DELETE request is - DELETE Http Method DELETE is a request method
2 min read
PUT method - Python requests
Requests library is one of the important aspects of Python for making HTTP requests to a specified URL. This article revolves around how one can make PUT request to a specified URL using requests.put() method. Before checking out the PUT method, let's figure out what a Http PUT request is - PUT Http Method PUT is a request method supported by HTTP
3 min read
PATCH method - Python requests
Requests library is one of the important aspects of Python for making HTTP requests to a specified URL. This article revolves around how one can make PATCH request to a specified URL using requests.patch() method. Before checking out the PATCH method, let's figure out what a Http PATCH request is - PATCH Http Method PATCH is a request method suppor
3 min read
POST method - Python requests
Requests library is one of the important aspects of Python for making HTTP requests to a specified URL. This article revolves around how one can make POST request to a specified URL using requests.post() method. Before checking out the POST method, let's figure out what a POST request is - POST Http Method POST is a request method supported by HTTP
2 min read
GET method - Python requests
Requests library is one of the important aspects of Python for making HTTP requests to a specified URL. This article revolves around how one can make GET request to a specified URL using requests.GET() method. Before checking out GET method, let's figure out what a GET request is - GET Http Method The GET method is used to retrieve information from
2 min read
Http Request methods - Python requests
Python requests module has several built-in methods to make Http requests to specified URI using GET, POST, PUT, PATCH or HEAD requests. A Http request is meant to either retrieve data from a specified URI or to push data to a server. It works as a request-response protocol between a client and server. A web browser may be the client, and an applic
7 min read
response.headers - Python requests
Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would be used to access certain features such as content, headers, etc. This article revolves around how to check the response.headers out of a
2 min read
response.elapsed - Python requests
Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would be used to access certain features such as content, headers, etc. This article revolves around how to check the response.elapsed out of a
2 min read
response.close() - Python requests
Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would be used to access certain features such as content, headers, etc. This article revolves around how to check the response.close() out of a
2 min read
response.content - Python requests
Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would be used to access certain features such as content, headers, etc. This article revolves around how to check the response.content out of a
2 min read
response.cookies - Python requests
Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would be used to access certain features such as content, headers, etc. This article revolves around how to check the response.cookies out of a
2 min read
response.history - Python requests
Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would be used to access certain features such as content, headers, etc. This article revolves around how to check the response.history out of a
2 min read
response.is_permanent_redirect - Python requests
Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would be used to access certain features such as content, headers, etc. This article revolves around how to check the response.is_permanent_redi
2 min read
response.is_redirect - Python requests
Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would be used to access certain features such as content, headers, etc. This article revolves around how to check the response.is_redirect out o
2 min read
response.iter_content() - Python requests
response.iter_content() iterates over the response.content. Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would be used to access certain features such as content, headers, etc. This article
2 min read
response.url - Python requests
response.url returns the URL of the response. It will show the main url which has returned the content, after all redirections, if done. Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would b
2 min read
response.text - Python requests
response.text returns the content of the response, in unicode. Basically, it refers to Binary Response content. Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would be used to access certain
2 min read
response.status_code - Python requests
response.status_code returns a number that indicates the status (200 is OK, 404 is Not Found). Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would be used to access certain features such as
2 min read
response.request - Python requests
response.request returns the request object that requested this response. Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would be used to access certain features such as content, headers, etc
2 min read
response.reason - Python requests
response.reason returns a text corresponding to the status code. for example, OK for 200, Not Found for 404. Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would be used to access certain fea
2 min read
response.raise_for_status() - Python requests
response.raise_for_status() returns an HTTPError object if an error has occurred during the process. It is used for debugging the requests module and is an integral part of Python requests. Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns
2 min read
response.ok - Python requests
response.ok returns True if status_code is less than 400, otherwise False. Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would be used to access certain features such as content, headers, et
2 min read
response.links - Python requests
response.links returns the header links. To know more about Http Headers, visit - Http Headers. Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would be used to access certain features such as
2 min read
Response Methods - Python requests
When one makes a request to a URI, it returns a response. This Response object in terms of python is returned by requests.method(), method being - get, post, put, etc. Response is a powerful object with lots of functions and attributes that assist in normalizing data or creating ideal portions of code. For example, response.status_code returns the
5 min read
Authentication using Python requests
Authentication refers to giving a user permissions to access a particular resource. Since, everyone can't be allowed to access data from every URL, one would require authentication primarily. To achieve this authentication, typically one provides authentication data through Authorization header or a custom header defined by server. Example - # impo
2 min read
SSL Certificate Verification - Python requests
Requests verifies SSL certificates for HTTPS requests, just like a web browser. SSL Certificates are small data files that digitally bind a cryptographic key to an organization's details. Often, a website with a SSL certificate is termed as secure website. By default, SSL verification is enabled, and Requests will throw a SSLError if it’s unable to
2 min read
Session Objects - Python requests
Session object allows one to persist certain parameters across requests. It also persists cookies across all requests made from the Session instance and will use urllib3’s connection pooling. So, if several requests are being made to the same host, the underlying TCP connection will be reused, which can result in a significant performance increase.
2 min read
Network Programming Python - HTTP Requests
HTTP stands for HyperText Transfer Protocol, which works on the client-server machine. In most cases, the web browser acts as the client, and the computer which hosts the website acts as a server. Python provides the requests module to play with HTTP requests. The requests module plays a major role in HTTP requests, apart from simple request and th
2 min read
Practice Tags :