Python - Get Data through API with Bearer Token (I) - Data Collection

As a Python beginner, I’m going to complete my first formal research task by Python, getting data from one open databank through API. But token is needed to be provided. So the blog is divided into two parts: retrieving token and calling API.

My work is mainly based on the requests module in Python. [1] [2]

Retrieve Token

We need username and password (clinet_id and clinet_secret) to retrieve temporary token.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import requests

#Url consists of three parts
Url = 'domain' + 'path' + 'endpoint'

#Construct data params
Data = {
"grant_type" : "password",
"username" : "myusername",
"password" : "mypassword"
}

#Specify headers
Headers = {
"Content-Type" : "application/x-www-form-urlencoded"
}

#Request token by POST
res = requests.post(Url, data=Data, headers = Headers)

#Print returned results (including token)
print(res.json())

Here are the returned results:

1
2
#It contains token, token type and expiration time
{'access_token': 'xxxxxxx', 'refresh_token': 'yyyyyy', 'token_type': 'Bearer', 'expires_in': 86400}

Call API

Return status code to check whether your request works well. [3]

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

import requests,json
#Another url with different path and endpoint
Url = 'domain' + 'path' + 'endpoint'

#Construct token
token = res.json()["access_token"]
token ="Bearer" + " " + token #Remark: one blank " " between token type and token
#print(token)

#Specify headers, assigning token
Headers = {
"Authorization" : token,
"Content-Type" : "application/json"
}

#Specific json data params, depend on API
Data = {
"sys_take": "2",
"sys_skip": "0"
}

#Call for API
pro_res = requests.post(Url, headers = Headers, json = Data)
print(pro_res.status_code)
print(pro_res.text)

Here are returned results:

1
2
3
#If Error code 4xx or 5xx is returned, you need to check your code, especially headers. (json and data are two distinct params)
200
'text'

It should be noticed that, json() is successfully called does not mean your request works well. [4]


Python - Get Data through API with Bearer Token (I) - Data Collection
http://arwenzhou.github.io/2020/11/12/Python-requests-API_1/
Author
Arwen
Posted on
November 12, 2020
Licensed under