requests
Get
import requests

response = requests.get('https://api.github.com')

if response.status_code == 200:
    print('Success!')
elif response.status_code == 404:
    print('Not Found.')
		
import requests

response = requests.get('https://api.github.com/search/repositories',
    params={'q': 'requests+language:python'},
    headers={'Accept': 'application/vnd.github.v3.text-match+json'},
)

json_response = response.json()
print(json_response)
		
Exception
import requests
from requests.exceptions import HTTPError

try:
    response = requests.get('https://api.github.com/invalid')
    response.raise_for_status() # If the response was successful, no Exception will be raised
except HTTPError as http_err:
        print(http_err)

try:
    response = requests.get('https://api.github.com')
    response.raise_for_status() # If the response was successful, no Exception will be raised
except HTTPError as http_err:
    print(http_err)
else:
    print("success!")
		
Content
import requests
response = requests.get('https://api.github.com')

print(response.content) # bytes string

response.encoding = 'utf-8'
print(response.text) # unicode string

print(response.json()) # convert to json data
		
Headers
import requests
response = requests.get('https://api.github.com')

print(response.headers)
		
Others
import requests

response = requests.post('https://httpbin.org/post', data={'key':'value'})
print(response.text)

response = requests.put('https://httpbin.org/put', data={'key':'value'})
print(response.text)

response = requests.delete('https://httpbin.org/delete')
print(response.text)

response = requests.head('https://httpbin.org/get')
print(response.text)

response = requests.patch('https://httpbin.org/patch', data={'key':'value'})
print(response.text)

requests.options('https://httpbin.org/get')
print(response.text)
		
Inspections
import requests

response = requests.post('https://httpbin.org/post', json={'key':'value'})
request = response.request

print(request.headers);
print(request.url)
print(request.body)
		
Authentication
#access by username and password
import requests

from getpass import getpass
response = requests.get('https://api.github.com/user', auth=('username', getpass()))
		
#access by token
import requests

headers = {
    'Authorization': 'Bearer AAAAAAAAAAAAAAAAAAAAAIRWAwEAAAAALRrtvjL3wDGnv%2FuA0EO463TjzLc%3DzuLJ3ypKMwrp59WQ4fY6TuAKXN1jqq4VEj4TDx9AFAzWj9qeg4',
}

data = '{"query":"Valdosta State","maxResults":"100","fromDate":"201910200000","toDate":"201910310000"}'

response = requests.post('https://api.twitter.com/1.1/tweets/search/30day/SearchThirtyDays.json', headers=headers, data=data)
		
Reference
  • Tutorial