2.6 Case Studies of Python API Calling
Key Points
- Introduction to POSTMAN CODE
- Demo of Python API calling
Preparation Before Class
None.
Course Content
POSTMAN CODE
(Demo - Use POSTMAN to quickly generate code for API calling)
Demo of Jodoo
(Demo - Use the Requests and import json to define functions for calling Jodoo APIs)
- Copy POSTMAN's CODE to Python, and be careful that the Body should be replaced with the content of the POSTMAN Body (it's better to use the original JSON).
import requests
url = "https://api.jodoo.com/api/v1/app/637c4093feed76000732fa2b/entry/63aaac0462223e000761aeb6/data_retrieve"
#Before replacing the Body
payload = "{\r\n \"data_id\": \"64631f6c5406fe0007f66c45\"\r\n}"
#After replacing the Body
payload = {
"data_id": "64631f6c5406fe0007f66c45"
}
headers = {
'Authorization': 'Bearer xxxxxxx',
'Content-Type': 'application/json',
'Cookie': 'JODOO_SID=s%3AkkffLPwwM05AA85K8IdYsXPF0zB-I0fi.GLHEBt5s61l9x0S7idpqYTFPIoUccDRv4IdXRYertCU; DEV_SID=s%3AdpxME_zPEoygRg8TxawKi6TQsalZ8p-V.mYUJRUHwMd95JFvz1tg2Zssl%2B4a%2BQRVq%2FGSckENfixY'
}
response = requests.request("POST", url, headers=headers, data = payload)
print(response.text.encode('utf8'))
- Define a function, replace the payload parameter with the function's variable, and be careful to convert payload to JSON.
import requests
import json
def jodoo(dataid):
url = "https://api.jodoo.com/api/v1/app/637c4093feed76000732fa2b/entry/63aaac0462223e000761aeb6/data_retrieve"
payload = {
"data_id": dataid
}
headers = {
'Authorization': 'Bearer xxxxxxxxx',
'Content-Type': 'application/json',
'Cookie': 'JODOO_SID=s%3AkkffLPwwM05AA85K8IdYsXPF0zB-I0fi.GLHEBt5s61l9x0S7idpqYTFPIoUccDRv4IdXRYertCU; DEV_SID=s%3AdpxME_zPEoygRg8TxawKi6TQsalZ8p-V.mYUJRUHwMd95JFvz1tg2Zssl%2B4a%2BQRVq%2FGSckENfixY'
}
#Replace payload with Json
response = requests.request("POST", url, headers=headers, data = json.dumps(payload))
#Just print response.text,requests will automatically encode bytes into strings.
print(response.text)
- Now it's time to call the function!
jodoo("64631f6c5406fe0007f66c45")