Skip to main content

Requests Module in Python

 


Learning Sections          show

Requests Module in Python

The requests module in Python is a popular library used to make HTTP requests in a simple and human-friendly way. It abstracts the complexities of making requests behind a simple API, allowing you to send HTTP requests with minimal effort.


Installing Requests

You can install the requests module using pip:


$ pip install requests
    

Making a Simple GET Request

The most common use of the requests module is to send a GET request to retrieve data from a server:


import requests as r

# Make a GET request
response = r.get('https://api.github.com')
# Print the response text
print(response.text)
    

The get function sends a GET request to the specified URL and returns a response object, which you can use to access various elements of the response.


Handling Response Content

The response object contains all the data returned by the server, and you can access different parts of it:


# Print response status code
print(response.status_code)

# Print response headers
print(response.headers)

# Print response JSON content
print(response.json())
    

You can access the response's status code, headers, and content in various formats such as text, JSON, or binary.


Making a POST Request

You can send data to the server using the POST method:


# Define the data to send in the POST request
data = {
    'key1': 'value1',
    'key2': 'value2'
}

# Make a POST request
response = r.post('https://httpbin.org/post', data=data)

# Print the response text
print(response.text)
    

The post function sends a POST request with the specified data to the server.


Handling URL Parameters

You can pass parameters in the URL of a GET request using the params keyword:


# Define the URL parameters
params = {
    'param1': 'value1',
    'param2': 'value2'
}

# Make a GET request with URL parameters
response = r.get('https://httpbin.org/get', params=params)

# Print the response text
print(response.text)
    

The params keyword allows you to include URL parameters in your GET request.


Uploading Files

You can upload files using the files keyword:


# Define the file to upload
files = {
    'file': ('filename.txt', open('filename.txt', 'rb'))
}

# Make a POST request to upload the file
response = r.post('https://httpbin.org/post', files=files)

# Print the response text
print(response.text)
    

Handling Authentication

The requests module supports different types of authentication, such as Basic Authentication:


from requests.auth import HTTPBasicAuth

# Make a GET request with Basic Authentication
response = r.get(
    'https://api.github.com/user',
    auth=HTTPBasicAuth('username', 'password')
)

# Print the response text
print(response.text)
    

The auth keyword allows you to include authentication details in your request.


Session Objects

Session objects allow you to persist parameters across multiple requests:


# Create a session object
session = r.Session()

# Define the URL parameters
session.params = {
    'param1': 'value1',
    'param2': 'value2'
}

# Make a GET request with the session
response = session.get('https://httpbin.org/get')

# Print the response text
print(response.text)
    

Session objects can be used to persist certain parameters, such as cookies and headers, across multiple requests.


Custom Headers

You can send custom headers in your requests using the headers keyword:


# Define the custom headers
headers = {
    'User-Agent': 'my-app/0.0.1'
}

# Make a GET request with custom headers
response = r.get('https://api.github.com', headers=headers)

# Print the response text
print(response.text)
    

The headers keyword allows you to send custom headers with your requests.


Timeouts

You can specify a timeout for your requests using the timeout keyword:


# Make a GET request with a timeout
response = r.get('https://api.github.com', timeout=5)

# Print the response text
print(response.text)
    

The timeout keyword specifies the maximum number of seconds to wait for a response.

Popular posts from this blog

Introduction to OOPs in Python

  Learning Sections          show Introduction to Object-Oriented Programming (OOP) Object-Oriented Programming (OOP) is a programming paradigm that organizes software design around objects rather than actions and data rather than logic. It revolves around the concept of "objects", which are instances of classes. These objects encapsulate data, in the form of attributes or properties, and behaviors, in the form of methods or functions. OOP promotes modularity, reusability, and extensibility in software development. Key Concepts of OOP: Class: A class is a blueprint or template for creating objects. It defines the attributes (data) and methods (functions) that will characterize any object instantiated from that class. Object: An object is an instance of a class. It is a concrete realization of the class blueprint, containing actual values instead of placeholders for attributes. Encapsulation: Encapsulation is ...

Classes and Objects in Python

  Learning Sections          show Classes and Objects in Python In Python, a class is a blueprint for creating objects. An object is an instance of a class. Classes allow you to logically group data and functions in a way that is easy to manage and reuse. 1. Defining a Class To define a class in Python, you use the class keyword followed by the class name and a colon. Inside the class, you can define attributes and methods. Example: # Define a class class Person : # Class attribute species = 'Human' # Class method def greet ( self ): return 'Hello, I am a person.' # Create an object of the class person1 = Person () # Access class attribute print ( person1 . species ) # Output: Human # Call class method print ( person1 . greet ()) # Output: Hello, I am a person. 2. Creating Objects To create an object of a class, you simply call the class name followed by paren...

Exception Handling in Python

  Learning sections          show Exception Handling in Python Exception handling in Python is done through the use of try , except , else , and finally blocks. This allows you to catch and handle errors gracefully. Below are some examples and explanations: 1. Basic Try-Except The try block lets you test a block of code for errors. The except block lets you handle the error. # Example of basic try-except try : result = 10 / 0 except ZeroDivisionError : print ( "Cannot divide by zero!" ) # Output: # Cannot divide by zero! 2. Handling Multiple Exceptions You can catch multiple exceptions by specifying multiple except blocks. # Example of handling multiple exceptions try : result = 10 / 0 except ZeroDivisionError : print ( "Cannot divide by zero!" ) except TypeError : print ( "Invalid operation!" ) # Output: # Cannot divide by zero! 3. Using Else The e...