Python Requests Query
Python Requests is a popular HTTP library that allows you to send HTTP/1.1 requests extremely easily. With Python Requests, you can easily query an API or scrape a website, etc. Python Requests module allows us to send HTTP requests using Python. The HTTP request returns a Response Object with all the response content (HTML, CSS, JavaScript, etc.).
There are different types of requests that you can send using Python Requests module such as GET, POST, PUT, DELETE, etc. Here we will discuss how to send a GET request using Python requests module.
Sending a GET Request in Python
To send a GET request in Python, you can use the requests.get()
method. This method takes a single argument which is the URL of the resource that you want to retrieve.
import requests
response = requests.get('https://jsonplaceholder.typicode.com/posts')
print(response.status_code)
print(response.json())
In the above code snippet, we are sending a GET request to the JSONPlaceholder API to retrieve all posts. We are using the requests.get()
method to send the request and passing in the URL of the API as an argument. The response object that we get back contains the status code of the response (200 in this case) and the content of the response in JSON format.
Query Parameters in Requests
Query parameters are a way to pass additional data to a GET request. Query parameters are included in the URL after a question mark (?) and separated by an ampersand (&). In Python Requests, you can pass query parameters using the params
parameter of the requests.get()
method.
import requests
params = {'userId': 1}
response = requests.get('https://jsonplaceholder.typicode.com/posts', params=params)
print(response.status_code)
print(response.json())
In the above code snippet, we are passing a query parameter userId=1
to the JSONPlaceholder API to retrieve all posts by the user with ID 1. We are using the params
parameter of the requests.get()
method to pass the query parameter.
HTTP Headers in Requests
HTTP headers are used to send additional information with an HTTP request. In Python Requests, you can pass headers using the headers
parameter of the requests.get()
method.
import requests
headers = {'Authorization': 'Bearer MY_TOKEN'}
response = requests.get('https://api.example.com/data', headers=headers)
print(response.status_code)
print(response.json())
In the above code snippet, we are passing an Authorization header with a bearer token to an API endpoint. We are using the headers
parameter of the requests.get()
method to pass the header.
Conclusion
Python Requests is a very powerful and easy-to-use HTTP library in Python. In this article, we discussed how to send a GET request using Python Requests and how to pass query parameters and HTTP headers using this library. You can use these techniques to interact with any API or website that exposes an HTTP interface.