python requests module example

hljs.initHighlightingOnLoad();

Python Requests Module Example

If you want to make HTTP requests in Python, the requests module is a great choice. It allows you to send HTTP/1.1 requests extremely easily. In this article, I'll show you some examples of how to use it.

Installation

You can install requests using pip:

pip install requests

GET Request

The simplest type of request is a GET request. This is used to retrieve data from a server. Here's an example:

import requests

response = requests.get('https://jsonplaceholder.typicode.com/todos/1')
print(response.json())

The above code will send a GET request to the URL 'https://jsonplaceholder.typicode.com/todos/1' and print the response in JSON format.

POST Request

If you want to send data to a server, you can use a POST request. Here's an example:

import requests

data = {'username': 'example', 'password': 'secret'}
response = requests.post('https://httpbin.org/post', data=data)
print(response.json())

The above code will send a POST request to the URL 'https://httpbin.org/post' with the data {'username': 'example', 'password': 'secret'} and print the response in JSON format.

PUT Request

If you want to update existing data on a server, you can use a PUT request. Here's an example:

import requests

data = {'name': 'John Doe', 'age': 30}
response = requests.put('https://httpbin.org/put', data=data)
print(response.json())

The above code will send a PUT request to the URL 'https://httpbin.org/put' with the data {'name': 'John Doe', 'age': 30} and print the response in JSON format.

DELETE Request

If you want to delete data on a server, you can use a DELETE request. Here's an example:

import requests

response = requests.delete('https://httpbin.org/delete')
print(response.json())

The above code will send a DELETE request to the URL 'https://httpbin.org/delete' and print the response in JSON format.