EP-APIの呼び出しサンプル
サンプルコード
GET api_version を呼び出すサンプルコードをご紹介します。
下記のコードをep-api.pyというファイル名で保存します。
import base64 import hashlib import hmac import json import time import urllib.request endpoint = 'ep.api.iij.jp' api_version = '20190625' api_name = 'api_version' http_method = 'GET' access_key = b'YOUR ACCESS KEY HERE' secret_key = b'YOUR SECRET KEY HERE' signature_version = '2' signature_method = 'HmacSHA256' content_type = '' expire = time.strftime('%FT%H:%M:%SZ', time.gmtime(time.time() + 12 * 60 * 60)) # make signature path = '/r/{}/{}.json'.format(api_version, api_name) header_strings = content_type + '\n' header_strings += 'x-iijapi-expire' + ':' + expire + '\n' header_strings += 'x-iijapi-signaturemethod' + ':' + signature_method + '\n' header_strings += 'x-iijapi-signatureversion' + ':' + signature_version string_to_sign = '\n'.join([http_method.upper(), '', header_strings, path]) signature = hmac.new(secret_key, string_to_sign.encode('utf-8'), hashlib.sha256).digest() signature = base64.b64encode(signature) # make request headers = { 'Authorization': b'IIJAPI ' + access_key + b':' + signature, 'Content-Type': content_type, 'x-iijapi-Expire': expire, 'x-iijapi-SignatureMethod': signature_method, 'x-iijapi-SignatureVersion': signature_version, } https_handler = urllib.request.HTTPSHandler() opener = urllib.request.build_opener(https_handler) urllib.request.install_opener(opener) url = 'https://{}{}'.format(endpoint, path) # call EP-API request = urllib.request.Request(url, headers=headers) # must use TLS 1.2 or higher if hasattr(ssl, 'PROTOCOL_TLS'): context = ssl.SSLContext(ssl.PROTOCOL_TLS) context.options |= ssl.OP_NO_TLSv1 context.options |= ssl.OP_NO_TLSv1_1 else: context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) print(json.load(response))
実行例
下記の実行例は python 3.6.5 環境で実行しています。
$ python ep-api.py {'APIResult': {'RequestId': 'f9ba8be1-52dfb362-976062fa-0000db9f-d7d7668c', 'APIVersions': ['20190625']}}