EP-APIの呼び出しサンプル
サンプルコード
GET api_version を呼び出すサンプルコードをご紹介します。
下記のコードをep-api.pyというファイル名で保存します。
import base64 import contextlib import hashlib import hmac import json import ssl 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) # setup SSL context context = ssl.create_default_context() https_handler = urllib.request.HTTPSHandler(context=context) opener = urllib.request.build_opener(https_handler) urllib.request.install_opener(opener) # 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, } url = 'https://{}{}'.format(endpoint, path) request = urllib.request.Request(url, headers=headers) # call EP-API with contextlib.closing(urllib.request.urlopen(request)) as conn: response = conn.read() print(json.loads(response.decode()))
実行例
下記の実行例は python 3.10.12 環境で実行しています。
$ python ep-api.py {'APIResult': {'RequestId': 'f9ba8be1-52dfb362-976062fa-0000db9f-d7d7668c', 'APIVersions': ['20190625']}}