Python Requests Library: Making HTTP Requests for Humans
Python Requests Library: Making HTTP Requests
The Requests library for Python simplifies making HTTP requests, offering an elegant and user-friendly experience.
Making a Request
Start by importing the Requests module:
>>> import requests
To retrieve a webpage, such as GitHub’s public timeline, use the get
method:
>>> r = requests.get('https://api.github.com/events')
This creates a Response
object named r
containing information about the response.
Other HTTP Methods
Requests supports various HTTP methods with a consistent API. Here’s how to make POST, PUT, DELETE, HEAD, and OPTIONS requests:
>>> r = requests.post('http://httpbin.org/post', data={'key':'value'})
>>> r = requests.put('http://httpbin.org/put', data={'key':'value'})
>>> r = requests.delete('http://httpbin.org/delete')
>>> r = requests.head('http://httpbin.org/get')
>>> r = requests.options('http://httpbin.org/get')
Passing Parameters in URLs
To send data in the URL’s query string, use the params
keyword argument with a dictionary of key-value pairs. For example:
>>> payload = {'key1': 'value1', 'key2': 'value2'}
>>> r = requests.get('http://httpbin.org/get', params=payload)
This encodes the URL correctly, as shown by printing r.url
:
>>> print(r.url)
http://httpbin.org/get?key2=value2&key1=value1
Note that keys with None
values are excluded from the query string. You can also pass lists as values:
>>> payload = {'key1': 'value1', 'key2': ['value2', 'value3']}
>>> r = requests.get('http://httpbin.org/get', params=payload)
>>> print(r.url)
http://httpbin.org/get?key1=value1&key2=value2&key2=value3