Skip to content

Requests

Requests is an elegant and simple HTTP library for Python, built for human beings.

Installation

pip install requests

Usage

Download file

url = "http://beispiel.dort/ichbineinbild.jpg"
filename = url.split("/")[-1]
r = requests.get(url, timeout=0.5)

if r.status_code == 200:
    with open(filename, 'wb') as f:
        f.write(r.content)

Encode url

requests.utils.quote('/test', safe='')

Get

requests.get('{{ url }}')

Put url

requests.put({{ url }})

Put json data url

data = {"key": "value"}
requests.put({{ url }} json=data)

Use cookies between requests

You can use Session objects to persists cookies or default data across all requests.

s = requests.Session()

s.get('https://httpbin.org/cookies/set/sessioncookie/123456789')
r = s.get('https://httpbin.org/cookies')

print(r.text)
# '{"cookies": {"sessioncookie": "123456789"}}'

s.auth = ('user', 'pass')
s.headers.update({'x-test': 'true'})

# both 'x-test' and 'x-test2' are sent
s.get('https://httpbin.org/headers', headers={'x-test2': 'true'})

References


Last update: 2022-05-24