How to use Python Requests Library?
Python Requests library is a simple HTTP library for Python. It is used to send HTTP/1.1 requests extremely easily. This library provides methods to send HTTP requests, parse HTTP responses, and handle cookies. Requests library is widely used in Python for making HTTP requests to APIs.
Installation
Before using the Requests library, you need to install it. To install it, you can use pip, which is a package installer for Python. You can open up terminal or command prompt and run the following command.
pip install requests
Using Requests Library
To use the Requests library, you need to import it in your Python project.
import requests
Requests Library provides various methods such as GET, POST, PUT, DELETE, etc. to make API calls. Let's take a look at how we can use the GET method to make an API call.
import requests
response = requests.get('https://jsonplaceholder.typicode.com/posts')
print(response.status_code)
In the above example, we are making a GET request to the endpoint 'https://jsonplaceholder.typicode.com/posts'. We are printing the status code of the response returned by the API.
HTTP Methods using Requests Library
Requests library provides various methods to make HTTP requests.
- GET: To retrieve data from the server.
- POST: To submit an entity to the specified resource.
- PUT: To update an entity with the provided data.
- DELETE: To delete an entity specified by its identifier.
Let's take a look at how we can use these methods using the Requests library.
import requests
# GET Request
response = requests.get('https://jsonplaceholder.typicode.com/posts')
print(response.status_code)
# POST Request
data = {
'title': 'foo',
'body': 'bar',
'userId': 1
}
response = requests.post('https://jsonplaceholder.typicode.com/posts', data=data)
print(response.status_code)
# PUT Request
data = {
'id': 1,
'title': 'foo',
'body': 'bar',
'userId': 1
}
response = requests.put('https://jsonplaceholder.typicode.com/posts/1', data=data)
print(response.status_code)
# DELETE Request
response = requests.delete('https://jsonplaceholder.typicode.com/posts/1')
print(response.status_code)
In the above example, we are making HTTP requests using the Requests library. We are printing the status code of the responses returned by the API.