Javier Gonzalez
By Javier Gonzalez

Requests library in Python

Requests library in Python

Python Requests Library

Sometimes we need with a script written in Python accessing to an API or download the content of a web page.

For that we can use the Requests Library

First we need to install the library:

1
2
3

pip install requests

Code Example :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49


import requests



# The requests module provides us different methods (get, post, update, delete)

r = requests.get('http://www.google.com')



# In the request method also it is possible to specify the headers, the cookies and the data sent

headers = { 'accept' : '*/*' }

payload = { 'title' : 'Download web page with python' }

cookies = dict(example_cookie='value')



r = requests.post('https://reqres.in/api/posts', data=payload, headers=headers, cookies=cookies)



# With the object returned 

# We could check the status code of the response

r.status_code



# We could obtain the content of the page as a string

r.text



# Or if the url is an API, we could obtain the response in json format

r.json()