Easy to use Nifty Cloud API with botocore and python

This article is the 12th day article of NIFTY Advent Calendar 2016.

Yesterday was an article by @ alice02 A story about a Ruby study session among new employees. I was happy that my name came out a little.

I'm @umiiiiins, an apprentice engineer for the first year of Nifty graduates. Recently I was assigned to a department and had the opportunity to hit the Nifty Cloud API, so I would like to talk about hitting the very basic Nifty Cloud API easily with python.

Nifty Cloud API

Nifty Cloud provides various functions as API. There are 1 to 4 signature versions required to send a request, and the available signatures vary depending on the service. This time, we will use the Nifty Cloud Script API and signature version 4 as an example.

What is botocore

A low-level interface for AWS, currently used in the AWS CLI and boto3. Since the Nifty Cloud API signature is generated in the same way as AWS, you can use botocore. If you are interested, please check the source code in the botocore repository.

Preparation

Install Python (I'm using 3.5.2 this time) Perform Quick Start Of Nifty Cloud Script. Register the access key and secret key obtained from the red frame part of the image as ACCESS_KEY_ID and SECRET_ACCESS_KEY in the environment variables. [Control panel]Capture.JPG

Now I want to run the script.

Actually try

First, set the required request URL, header, and parameters by referring to Script API Reference.

script_api.py


url = "https://script.api.cloud.nifty.com/2015-09-01" 
headers = {
    'X-Amz-Target': '2015-09-01.ExecuteScript',
}
params = {
    'ScriptIdentifier': 'test.js',
    'Method': 'GET',
    'Header': '{}',
    'Body': '{}',
    'Query': '{"name":"Umino"}',
}

Next, use botocore to generate and request signatures. At this time, make sure that the method of the argument of AWSRequest is correct.

script_api.py


credentials = Credentials(os.environ["ACCESS_KEY_ID"],os.environ["SECRET_ACCESS_KEY"])
request = AWSRequest(method="POST",url=url,data=params,headers=headers)
SigV4Auth(credentials, "ExecuteScript",'east-1').add_auth(request)
response = BotocoreHTTPSession().send(request.prepare())

Import what you need and hit the above program ...

<?xml version='1.0' encoding='utf-8'?>
<executescriptresponse>
    <requestid>
        9b195209-c025-4522-8e6a-9840324f3fb6
    </requestid>
    <executescriptresult>
        <result>
            <responsestatus>
                200
            </responsestatus>
            <scriptidentifier>
                test.js
            </scriptidentifier>
            <requestquery>
                <![CDATA[{"name":"Umino"}]]>
            </requestquery>
            <requestbody>
                <![CDATA[{}]]>
            </requestbody>
            <responseheader>
                <![CDATA[{"Content-Type":"text/plain"}]]>
            </responseheader>
            <requestheader>
                <![CDATA[{}]]>
            </requestheader>
            <responsedata>
                <![CDATA[Umino]]>
            </responsedata>
            <status>
                200
            </status>
        </result>
    </executescriptresult>
</executescriptresponse>

It was successful and the results were returned. Please refer to the script at here.

A little commentary

This time, Signature is generated by various methods called in addAuth of SigV4Auth class. In addition to SigV4Auth, there are AigV2Auth that generates signature version 2, so you can easily generate usage signatures with the Nifty Cloud API by using these. If you try to compare the inside of the header before and after executing SigV4Auth, you can see that Authorization is added after execution.

Before signature generation

{
 'X-Amz-Target': '2015-09-01.ExecuteScript',
}

After signature generation

{
 'X-Amz-Target': '2015-09-01.ExecuteScript',
 'X-Amz-Date': '20161211T090451Z',
 'Authorization': 'AWS4-HMAC-SHA256 
               Credential=OOICPHKDBZZE9ZNGEBV7/20161211/east-1/ExecuteScript/aws4_request, 
               SignedHeaders=content-type;host;x-amz-date;x-amz-target,
               Signature=ffddxxxxxxxxxxxxxxxxxxxxxxxxxxxxd4',
}

Also, when I try to execute DescribeInstances of the server using SigV2Auth, the generated signature is added to the parameter after execution.

Before signature generation

{'AccessKeyId': 'OOICPHKDBZZE9ZNGEBV7',
 'Action': 'DescribeInstances', 'SignatureVersion': '2', 
 'Timestamp': '2016-12-11T18:28:03Z', 'SignatureMethod': 'HmacSHA256'
}

After signature generation

{'AccessKeyId': 'OOICPHKDBZZE9ZNGEBV7',
 'Action': 'DescribeInstances', 'SignatureVersion': '2', 
 'Timestamp': '2016-12-11T09:28:03Z', 'SignatureMethod': 'HmacSHA256',
 'Signature': 'FydxxxxxxxxxxxxxxxxxxxxxxxxxxxxxqRc='
}

Summary

This time, as an example of using botocore, I gave a script that may be rarely hit from python, but of course it can also be used for services other than scripts. When it comes to signature version 4, it is quite difficult to implement it by yourself, so please refer to it if you have trouble using the Nifty Cloud API from python.

Tomorrow is "Managing Ansible configuration information in Graph DB" by @ntoofu!

Recommended Posts

Easy to use Nifty Cloud API with botocore and python
[AWS] [GCP] I tried to make cloud services easy to use with Python
Use Trello API with python
Use Twitter API with Python
Use subsonic API with python3
How to use Service Account OAuth and API with Google API Client for python
Python: How to use async with
I tried follow management with Twitter API and Python (easy)
How to use OpenPose's Python API
How to use FTP with Python
Easy to use Jupyter notebook (Python3.5)
Easy modeling with Blender and Python
[Python] How to use Typetalk API
Operate Jupyter with REST API to extract and save Python code
[September 2020 version] Explains the procedure to use Gmail API with Python
Sample to use after OAuth authentication of BOX API with Python
How to use Python with Jw_cad (Part 2 Command explanation and operation)
How to install and use pandas_datareader [Python]
Fractal to make and play with Python
[Introduction to Python] Let's use foreach with Python
Use PIL and Pillow with Cygwin Python
Easy way to use Wikipedia in Python
Use Google Cloud Vision API from Python
python: How to use locals () and globals ()
How to use Python zip and enumerate
How to use GCP's Cloud Vision API
Easy! Use gensim and word2vec with MAMP.
Easy web scraping with Python and Ruby
How to use is and == in Python
Use Python and MeCab with Azure Functions
Challenge to create time axis list report with Toggl API and Python
Don't use your username and password to register with PyPI. Use API tokens
[Python] Easy introduction to machine learning with python (SVM)
Scraping tabelog with python and outputting to CSV
MessagePack-Try to link Java and Python with RPC
I want to use MATLAB feval with python
Firebase: Use Cloud Firestore and Cloud Storage from Python
Easy way to use Python 2.7 on Cent OS 6
Procedure to use TeamGant's WEB API (using python)
Text extraction with GCP Cloud Vision API (Python3.6)
Specify the Python executable to use with virtualenv
How to use the Google Cloud Translation API
The easiest way to use OpenCV with python
I want to use Temporary Directory with Python2
How to use tkinter with python in pyenv
[Python] How to use hash function and tuple.
Get Gmail subject and body with Python and Gmail API
Use Python and word2vec (learned) with Azure Databricks
Use Python / Django with Windows Azure Cloud Service!
[Python] Mention to multiple people with Slack API
I tried to automate internal operations with Docker, Python and Twitter API + bonus
WEB scraping with python and try to make a word cloud from reviews
[Python] Use JSON with Python
Easy to use Flask
Use mecab with Python3
Use DynamoDB with Python
Use Python 3.8 with Anaconda
Use python with docker
Easy to use SQLite3
[GCP] [Python] Deploy API serverless with Google Cloud Functions!
[BigQuery] How to use BigQuery API for Python -Table creation-