- Installation: If you haven’t already installed the
requests
library, you can do so using pip:bashCopy codepip install requests
- Importing: Import the
requests
library in your Python script or interactive session:pythonCopy codeimport requests
- Making GET Requests: You can make a simple GET request to a URL using the
requests.get()
function. Here’s an example:pythonCopy codeimport requests response = requests.get("https://www.example.com") # Check if the request was successful (HTTP status code 200) if response.status_code == 200: print(response.text) # Print the content of the response else: print("Request failed with status code:", response.status_code)
- Passing Parameters: You can include query parameters in your GET request by passing them as a dictionary to the
params
parameter ofrequests.get()
.pythonCopy codeimport requests params = {'param1': 'value1', 'param2': 'value2'} response = requests.get("https://www.example.com/api", params=params)
- Making POST Requests: To make a POST request, use
requests.post()
. You can include data or JSON payload in the request:pythonCopy codeimport requests data = {'key1': 'value1', 'key2': 'value2'} response = requests.post("https://www.example.com/api", data=data)
- Handling JSON Responses: If the response from the server is in JSON format, you can easily parse it:pythonCopy code
import requests response = requests.get("https://jsonplaceholder.typicode.com/posts/1") data = response.json()
- Handling Headers and Authentication: You can set request headers and handle authentication by passing them as parameters to the request functions.pythonCopy code
import requests headers = {'User-Agent': 'MyApp/1.0'} auth = ('username', 'password') response = requests.get("https://www.example.com", headers=headers, auth=auth)
These are the basics of using the requests
library in Python to make HTTP requests. You can explore more features and options in the official documentation: https://docs.python-requests.org/en/master/