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

Generators in Python

  Learning Sections          show Generators in Python Generators are a special type of iterator in Python that allow you to iterate over a sequence of items without storing them all in memory at once. They are useful for generating large sequences of data on-the-fly, or for processing data in a memory-efficient manner. Creating Generators In Python, generators are created using generator functions or generator expressions: # Generator function def my_generator ( n ): for i in range ( n ): yield i # Generator expression my_generator = ( i for i in range ( 10 )) A generator function uses the yield keyword to yield values one at a time, while a generator expression creates an anonymous generator. Iterating Over Generators You can iterate over the values produced by a generator using a for loop: for value in my_generator ( 5 ): print ( value ) This w...

Inheritance in Python

  Learning Sections          show Inheritance in Python Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a class to inherit attributes and methods from another class. The class that inherits is called the child class or subclass, and the class being inherited from is called the parent class or superclass. Basic Inheritance In Python, a child class inherits from a parent class by specifying the parent class in parentheses after the child class name. Example: class Animal : def __init__ ( self , name ): self . name = name def speak ( self ): raise NotImplementedError ( "Subclass must implement this method" ) class Dog ( Animal ): def speak ( self ): return "Woof!" class Cat ( Animal ): def speak ( self ): return "Meow!" # Create instances of Dog and Cat dog = Dog ( "Buddy" ) cat = Cat ( "Whiskers" ...

If else Conditional Statements in Python

  Learning Sections     show If-Else Conditional Statements Conditional statements allow you to execute different blocks of code based on certain conditions. The most common conditional statement is the if statement. It can be used alone, or combined with elif (else if) and else statements to handle multiple conditions. If Statement The if statement evaluates a condition, and if the condition is true, the block of code indented under the if statement is executed. # If statement example x = 10 if x >> 0 : print ( "x is positive" ) If-Else Statement The if-else statement adds an additional block of code that runs if the condition is false. # If-else statement example x = -10 if x >> 0 : print ( "x is positive" ) else : print ( "x is non-positive" ) If-Elif-Else Statement The if-elif-else statement allows you to check multiple conditions. The fir...