Request
Get a webpage
r = requests.get('https://api.github.com/events')
Requests
r = requests.post('https://httpbin.org/post', data = {'key':'value'}) # postr = requests.put('https://httpbin.org/put', data = {'key':'value'}) # putr = requests.delete('https://httpbin.org/delete') # deleter = requests.head('https://httpbin.org/get') # headr = requests.options('https://httpbin.org/get') # options
Passing parameters
in the normal way we send data in URL's query string, we use key/value pairs in the URL after a question mark like: httpbin.org/get?key=val
requests provides params
keyword argument
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.get('https://httpbin.org/get', params=payload)
print(r.url)
# https://httpbin.org/get?key2=value2&key1=value1
# pass a list of items as a value:
payload = {'key1': 'value1', 'key2': ['value2', 'value3']}
r = requests.get('https://httpbin.org/get', params=payload)
print(r.url)
# https://httpbin.org/get?key1=value1&key2=value2&key2=value3
Response
r.encoding
You can find out what encoding Requests is using, and change it, using the r.encoding
property:
r.encoding
# 'utf-8'
r.encoding = 'ISO-8859-1'
r.json
In case the JSON decoding fails, r.json()
raises an exception. For example, if the response gets a 204 (No Content), or if the response contains invalid JSON