Convert the cURL API to a Python script (using IBM Cloud object storage)

Make a note of the conversion pattern when rewriting to Python after checking the operation of REST-API with cURL

  1. Use IBM Cloud object storage to verify the behavior of cURL.
  2. Write the confirmed cURL in a Python script and inspect it in the object storage.

Part 1. Get an authentication token

For cURL

curl -X "POST" "https://iam.cloud.ibm.com/identity/token" \
     -H 'Accept: application/json' \
     -H 'Content-Type: application/x-www-form-urlencoded' \
     --data-urlencode "apikey={api-key}" \
     --data-urlencode "response_type=cloud_iam" \
     --data-urlencode "grant_type=urn:ibm:params:oauth:grant-type:apikey"

For Python

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import requests
import json

#Get a token
headers = {
    'Accept': 'application/json',
    'Content-Type': 'application/x-www-form-urlencoded',
}
data = {
    'apikey': os.environ['IBM_APIKEY'],
    'response_type': 'cloud_iam',
    'grant_type': 'urn:ibm:params:oauth:grant-type:apikey'
}
response = requests.post('https://iam.cloud.ibm.com/identity/token', headers=headers, data=data)
print(response)
output = response.json()
#print(json.dumps(output, indent=4))

ibm_access_token = output['access_token']

print(ibm_access_token)

Python execution result

STATUS :<Response [200]>

{
"access_token":"eyJraWQ******************************************2Erh-Te-w",
"expires_in":3600,
}
#Very long tokens are valid for 1 hour (3600)=60 seconds x 60 minutes)

Part 2. View a list of buckets

For cURL

curl "https://(endpoint)/" \
 -H "Authorization: bearer (token)" \
 -H "ibm-service-instance-id: (resource-instance-id)"

For Python

#Write the same python script until you get the token
# “#!/usr/bin/env from python to ibm_access_token = output['access_token']Until"
#I will omit it here.

#List of objects
headers = {
    'Authorization': 'bearer ' + ibm_access_token
}
response = requests.get('https://s3.jp-tok.cloud-object-storage.appdomain.cloud/robocamera', headers=headers)
print("STATUS :" + str(response))
print("HEADERS:" + str(response.headers))
print("TEXT   :" + str(response.text))

Python execution result

STATUS :<Response [200]>
HEADERS:{'Content-Length': '1938', 'ibm-sse-kp-enabled':<Omitted>'Content-Type': 'application/xml'}
TEXT   :<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Omitted>

        <Name>robocamera</Name>
        <Contents>
            <Key>ciel_face_s.png</Key><LastModified>2019-11-30T02:50:53.410Z</LastModified>
            <Key>ghostpicture.jpg</Key><LastModified>2019-11-30T01:46:52.413Z</LastModified>
            <Key>index.html</Key><LastModified>2019-11-24T14:48:55.793Z</LastModified>

Part 3. Upload the file to the bucket

For cURL

curl -X "PUT" "https://(endpoint)/(bucket-name)/(object-key)" \
 -H "Authorization: bearer (token)" \
 -H "Content-Type: (content-type)" \
 -d "(object-contents)"

For Python

#Upload the camera image file to IBM Cloud Object Storage.
#In this example[/robocamera]Is the bucket name,[ghostpicture.jpg]Is the key name of the object.
    headers = {
        'Authorization': 'bearer ' + ibm_access_token,
        'Content-Type': 'image/jpeg',
    }
    f = open('capture_output.jpg', 'rb')
    img_data = f.read()
    f.close()
    response = requests.put(service_endpoint + '/robocamera/ghostpicture.jpg', headers=headers, data=img_data)
    #When you want to check when debugging token acquisition
    print("UPLOAD STATUS:" + str(response))

Oops. There was a site that converted cURL and Python scripts.

This is convenient.

Convert curl syntax to Python https://curl.trillworks.com/

Recommended Posts

Convert the cURL API to a Python script (using IBM Cloud object storage)
[Python] Change the Cache-Control of the object uploaded to Cloud Storage
Upload files to Aspera that comes with IBM Cloud Object Storage (ICOS) using SDK (Python version)
I made a script to record the active window using win32gui of Python
[IBM Cloud] Place the ISO file in the object storage
A little bit from Python using the Jenkins API
[Python] You can save an object to a file by using the pickle module.
A story about a Python beginner trying to get Google search results using the API
Creating a Python script that supports the e-Stat API (ver.2)
Tweet Now Playing to Twitter using the Spotify API. [Python]
I wrote a Python script that exports all my posts using the Qiita API v2
[OCI] Python script to get the IP address of a compute instance in Cloud Shell
I tried to automate the construction of a hands-on environment using IBM Cloud's SoftLayer API
Using Cloud Storage from Python3 (Introduction)
I created a Python library to call the LINE WORKS API
How to get followers and followers from python using the Mastodon API
Create a shell script to run the python file multiple times
[Cloudian # 2] Try to display the object storage bucket in Python (boto3)
A note about connecting Spark to OpenStack Swift-based IBM Object Storage
A script that returns 0, 1 attached to the first Python prime number
Regularly upload files to Google Drive using the Google Drive API in Python
How to send a request to the DMM (FANZA) API with python
Create a command line tool to convert dollars to yen using Python
How to upload a file to Cloud Storage using Python [Make a fixed point camera with Raspberry PI # 1]
Try using the Wunderlist API in Python
Try using the Kraken API in Python
[Python] How to convert a 2D list to a 1D list
Tweet using the Twitter API in Python
Run the Python interpreter in a script
I made a script in python to convert .md files to Scrapbox format
Operate Sakura's cloud object storage from Python
How to run a Maya Python script
I tried to deliver mail from Node.js and Python using the mail delivery service (SendGrid) of IBM Cloud!
I tried using the BigQuery Storage API
Try to build a pipeline to store the result in Bigquery by hitting the Youtube API regularly using Cloud Composer
[2015/11/19] How to register a service locally using the python SDK on naoqi os
Let Python measure the average score of a page using the PageSpeed Insights API
[Circuit x Python] How to find the transfer function of a circuit using Lcapy
The key to deploying Flask apps using Python Buildpack on Cloud Foundry (Diego)
I tried using the Python library "pykakasi" that can convert kanji to romaji.
[Python] Smasher tried to make the video loading process a function using a generator
[IBM Cloud] I tried to access the Db2 on Cloud table from Cloud Funtions (python)
Python script to get a list of input examples for the AtCoder contest
To automatically send an email with an attachment using the Gmail API in Python
Continue to retrieve tweets containing specific keywords using the Streaming API in Python
Created a Python wrapper for the Qiita API
Procedure to use TeamGant's WEB API (using python)
Python script to convert latitude / longitude to mesh code
Try using the BitFlyer Ligntning API in Python
I tried using the Google Cloud Vision API
How to generate a Python object from JSON
How to use the Google Cloud Translation API
Save the object to a file with pickle
Convert STL to Voxel mesh using Python VTK
Write a script to convert a MySQL dump to TSV
A python amateur tries to summarize the list ②
Run a python script from excel (using xlwings)
[Python] Throw a message to the slack channel
Try using the DropBox Core API in Python
Create a python script to check if the link at the specified URL is valid 2
I tried to notify the update of "Become a novelist" using "IFTTT" and "Become a novelist API"