Skip to content

Instantly share code, notes, and snippets.

@1UC1F3R616
Last active May 25, 2020 10:32
Show Gist options
  • Save 1UC1F3R616/ad7a7da368d12e79ad2669774c651792 to your computer and use it in GitHub Desktop.
Save 1UC1F3R616/ad7a7da368d12e79ad2669774c651792 to your computer and use it in GitHub Desktop.

finding all available methods

import requests
HEADER = {'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'}
r = requests.get('https://xkcd.com/353/') # headers = HEADER
print(help(r)) # *r* gives response

Content of the response

r.text # You can parse this using html parser, we have html/source code right now
print(r.status_code) # gives the status code
print(r.ok) # returns True if below 400
print(r.headers) # Gives the header

Downloading image / Getting data in bytes

r.content # Gives data in bytes

# Writing the byte data to get an image, just like an image download
import requests
r = requests.get('https://imgs.xkcd.com/comics/python.png')
with open('comic.png', 'wb') as f:
  f.write(r.content)

get request with params

import requests
payload = {'page':2, 'count':25}
r = requests.get('https://httpbin.org/get', params=payload)
print(r.text)
print(r.url) # To get te url inform of error prone format

post request with params

import requests
import json
payload = {'username':'kush', 'password':'testing'}
r = requests.post('https://httpbin.org/post', data=json.dumps(payload))
print(r.json()) # It returns the dict format

# Example 2
import requests
import json
payload = {'username':'kush', 'email':'mail@mail83', 'password':'123456'}
headers = {'content-type': 'application/json'}
url = 'https://painhost99.herokuapp.com/user/signup'
r = requests.post(url, data=json.dumps(payload), headers=headers)

Authentication code

import requests
r = requests.get('https://httpbin.org/basic-auth/kush/123456', auth=('kush', '123456'), timeout=3)
print(r.text) # returns a response

Misc

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment