{Python}REST API


https://qiita.com/hoto17296/items/8fcf55cc6cd823a18217
https://waku-take-a.blogspot.com/2019/05/python3basic.html
https://blog.kyanny.me/entry/2021/10/06/012946
https://docs.python.org/ja/3/library/index.html

https://qiita.com/hisshi00/items/9806eceeee2237624222
https://requests-docs-ja.readthedocs.io/en/latest/

 

(1) urllibライブラリの場合 (標準ライブラリのみ使用)

(1-1) GET


import urllib.request
import base64
import json


url = 'http://localhost:9090/webadmin/denodo-scheduler-admin/public/api/projects?uri=//localhost:8000'

user = "admin"
passwd = "admin"

user_pass = base64.b64encode("{0}:{1}".format(user, passwd).encode("utf-8"))
headers = { "Authorization" : "Basic " + user_pass.decode("utf-8"), 'content-type': 'application/json' }


req = urllib.request.Request(url , None, headers)

with urllib.request.urlopen(req) as res:
    print("status = {0}".format(res.status))
    print(res.read().decode('utf8'))

with urllib.request.urlopen(req) as res:
    body = json.load(res)
    print(body)
    print(body[0])
    print(body[0]["id"])

 

(1-2) POST


import urllib.request
import base64
import json


url = 'http://localhost:9090/webadmin/denodo-scheduler-admin/public/api/projects?uri=//localhost:8000'

user = "admin"
passwd = "admin"

user_pass = base64.b64encode("{0}:{1}".format(user, passwd).encode("utf-8"))
headers = { "Authorization" : "Basic " + user_pass.decode("utf-8"), 'content-type': 'application/json' }

json_data = { "name": "project12345", "description": "description of project12345"}

req = urllib.request.Request(url , json.dumps(json_data).encode(), headers )


with urllib.request.urlopen(req) as res:
    print("status = {0}".format(res.status))
    print(res.read().decode('utf8'))

 

 

(2) Requestsライブラリの場合 (requestsのインストール必要)


(2-1) GET

import requests
import json

url = 'http://localhost:9090/webadmin/denodo-scheduler-admin/public/api/projects?uri=//localhost:8000'
headers = {'content-type': 'application/json'}

r = requests.get(url, auth=('admin', 'admin'), headers=headers)

r.status_code
r.text
r.json()


(2-2) POST


import requests
import json

url = 'http://localhost:9090/webadmin/denodo-scheduler-admin/public/api/projects?uri=//localhost:8000'
headers = {'content-type': 'application/json'}

json_data = { "name": "project12345", "description": "description of project12345"}


r = requests.post(url, auth=('admin', 'admin'), headers=headers, data=json.dumps(json_data) )


r.status_code
r.text
r.json()