Python

データストレージ API

Python
sample.py
# coding: utf-8

# This is a sample python script code for IIJ IoT Data Storage Web API.
# For more information please refer to the manual.

from datetime import datetime

import requests
import hmac
import base64
import hashlib

BASE_URL = "https://s3api.iot.iij.jp"  # not edit
HOST = "s3api.iot.iij.jp"              # not edit

access_key = ""                  # your access key
secret_key = ""                  # your secret key
content_md5 = ""                 # if you upload file, you have to write.
content_type = ""                # not edit
date = datetime.utcnow().strftime("%a, %d %b %Y %H:%M:%S GMT")  # now date
payload = {}                     # if you needed. We expect xml.
content_length = len(payload)    # request body length
http_verb = 'GET'                # or POST, PUT, DELETE, HEAD
bucket_name = "/sample"          # specify your bucket
query = ""                       # if you needed. e.g. ?id=hoge
canonicalized_headers = ""       # if you use optional headers, you may write.
canonicalized_resource = bucket_name + query

string2sign = "\n".join([http_verb, content_md5, content_type, date, canonicalized_headers + bucket_name])

# create signature
signature = base64.b64encode(hmac.new(secret_key.encode("utf-8"), string2sign.encode("utf-8"), hashlib.sha1).digest())
# Example when using python3 (using decode)
#signature = base64.b64encode(hmac.new(secret_key.encode("utf-8"), string2sign.encode("utf-8"), hashlib.sha1).digest()).decode("utf-8")

headers = {
    "Authorization": "IIJGIO %s:%s" % (access_key, signature),
    "Content-Type": content_type,
    "Content-Length": str(content_length),
    "Content-MD5": content_md5,
    "Date": date,
    "Host": HOST,
}

url = BASE_URL + canonicalized_resource
request = requests.get(url, headers=headers)

print("Status Code: {}".format(request.status_code))
print("Body:\n{}".format(request.text))