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 ...

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" ...

read(), readlines() and other methods in Python

Learning Sections          show read(), readlines() and Other Methods in Python Python provides several methods to read from and manipulate files. Here are some common methods: 1. read() The read() method reads the entire content of a file and returns it as a string. # Open the file in read mode with open ( 'example.txt' , 'r' ) as file : # Read the entire content of the file content = file . read () print ( content ) 2. readlines() The readlines() method reads all the lines of a file and returns a list where each element is a line in the file. # Open the file in read mode with open ( 'example.txt' , 'r' ) as file : # Read all lines of the file lines = file . readlines () for line in lines : print ( line . strip ()) # strip() removes the newline character 3. readline() The readline() method reads one line from the file and returns it as a...