-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconsuming_REST_APIs_example.py
More file actions
48 lines (41 loc) · 1.89 KB
/
consuming_REST_APIs_example.py
File metadata and controls
48 lines (41 loc) · 1.89 KB
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
# this code is based on tutorial for using python and REST API under
# https://realpython.com/api-integration-in-python/
import requests
# some test for retrieving all entries response from REST API
api_url = "http://jsonplaceholder.typicode.com/todos"
response = requests.get(api_url)
print(f'(GET) Jason: {response.json()}')
print(f'(GET) Code: {response.status_code}')
# some test for retrieving all entries response from REST API
api_url = "http://jsonplaceholder.typicode.com/todos/1"
response = requests.get(api_url)
print(f'(GET one) Jason: {response.json()}')
print(f'(GET one) Code: {response.status_code}')
# some test for POST data on REST API
api_url = "http://jsonplaceholder.typicode.com/todos"
todo = {"userId": 1, "title": "Buy milk", "completed": False}
response = requests.post(api_url, json=todo)
print(f'(POST) Jason: {response.json()}')
print(f'(POST) Code: {response.status_code}')
# some test for POST data on REST API without setting json attribute
# on request
import json
api_url = "http://jsonplaceholder.typicode.com/todos"
todo = {"userId": 1, "title": "Buy milk", "completed": False}
headers = {"Content-Type":"application/json"}
response = requests.post(api_url, data=json.dumps(todo), headers=headers)
print(f'(POST Content-type) Jason: {response.json()}')
print(f'(POST Content-type) Code: {response.status_code}')
# some test for PATCH (change specific info) data on REST API
api_url = "http://jsonplaceholder.typicode.com/todos/10"
response = requests.get(api_url)
print(f'(PATCH) {response.json()}')
todo = {"title": "Mow lawn"}
response = requests.patch(api_url, json=todo)
print(f'(PATCH) Jason: {response.json()}')
print(f'(PATCH) Code: {response.status_code}')
# some test for DELETE data on REST API
api_url = "http://jsonplaceholder.typicode.com/todos/10"
response = requests.delete(api_url)
print(f'(DELETE) Jason: {response.json()}')
print(f'(DELETE) Code: {response.status_code}')