Develop Python Code that Uses the Oracle API Platform Cloud Service Management Service REST APIs

Use the Oracle API Platform Cloud Service Management APIs to create and deploy APIs that are located under the /apiplatform/management/v1/apis endpoint in your Oracle API Platform Cloud Service instance.

たとえば、完全なURLはhttps://YOUR-API-PCS-INSTANCE-URL/apiplatform/management/v1/apisです。

APIデータ・ファイルの作成

カンマ区切りファイル(CSV)などのコンピュータ解析可能なデータ・ファイルを作成して、Oracle API Platform Cloud ServiceポータルにアップロードするAPIを定義できます。

APIをOracle API Platform Cloud Serviceに公開する前に、API、命名規則、説明、バックエンドURLなど、すべての情報を定義および検証できるデータ・ファイルを作成すると便利です。

CSVデータ・ファイルの作成

CSVファイルは、すべてのAPIフィールドを列としてリストし、行に値を追加できるため、APIデータ・ファイルを作成する便利な方法です。

CSVテンプレート・ファイルを作成するには:

  1. テキスト・エディタまたはスプレッドシート・ソフトウェアを開き、Oracle API Platform Cloud Service APIポータルにアップロードするAPIの詳細を追加します。
  2. ファイルに、これらの6つのフィールドを列として入力します。
    • API_NAME: 作成するAPIの名前を指定します。各APIには一意の名前が必要です。
    • API_VERSION: 作成するAPIのバージョンを指定します。
    • API_DESCRIPTION: APIの詳細な説明を指定します。
    • API_URI: APIのエンドポイントURLを指定します。これはゲートウェイURLに追加されます。各APIには一意のURIが必要です。
    • SERVICE_URL: APIがリクエストを受信したときに呼び出されるバックエンド・サービスURL。
    • GATEWAY_ID: APIをゲートウェイにデプロイする場合にのみゲートウェイIDを指定します。それ以外の場合は、値 NONEを指定します。NONE値が指定されている場合、APIは配備されません。

    エラーの解析やファイルの破損を回避するために、CSVテンプレート・ファイルに空白の値を入れないでください。

  3. ファイルを保存します。

構成ファイルを作成してください

ユーザー名、RESTエンドポイントURL、REST Webサービスへのリクエスト・ペイロードとして使用されるJSONテンプレートなどの接続詳細を格納する構成ファイルを作成できます。

構成ファイルを作成するには:

  1. エディタを開き、共通変数を宣言します。
    api_file_name = "APIList.csv"
    
    ## Common variable declaration
    headers = {'Content-length' : '0', 'Content-type' : 'application/json'}
    user='YOUR-USER-NAME'
    apip_url = 'https://YOUR-API-PCS-INSTANCE-URL/apiplatform'
    
  2. APIポータル変数を宣言します。これらの変数は、APIを作成するためにメイン・クライアント・スクリプトで使用されます。
    ## API portal variables
    
    createAPI_REST = apip_url+'/management/v1/apis'
    api_create_json_str = '''{
                "name":"%s",
                "vanityName": "%s",
                "version": "%s",
                "description":"%s",
                "implementation":
                {
                    "policies":[
                            { "id":"1", "type":"o:ApiRequest", "version":"1.0", "draft":false, "config": {"protocols": ["HTTP"],"url": "%s"}},
                            { "id":"2", "type":"o:ServiceRequest", "version":"1.0", "draft":false, "config": {"headerConfig": {"action": "PASS-THROUGH","headersToAddOrUpdate": [], "headersToDrop": []},"useProxy": false,"url": "%s"}},
                            { "id":"3", "type":"o:ServiceResponse", "version":"1.0", "config":{}},
                            { "id":"4", "type":"o:ApiResponse", "version":"1.0", "config":{}}
                    ],
                    "executions":{ "request":["1","2"], "response":["3","4"] }
                }
            }'''
  3. APIゲートウェイ変数を宣言します。これらの変数は、APIをデプロイするためにメイン・クライアント・スクリプトで使用されます。
    ## API Gateway variables
    
    deployAPI_REST = apip_url+'/management/v1/apis/%s/deployments'        
    gw_deploy_json_str = '''{"gatewayId":"%s","action":"DEPLOY","description":"","runtimeState":"ACTIVE"}'''
    
  4. ファイルをConfig.pyとして保存します。

Pythonを使用したRESTクライアントの作成

Pythonプログラミング言語を使用して単純なRESTクライアントを開発し、APIをOracle API Platform Cloud Serviceにアップロードできます。

次のコード・スニペットは説明のみを目的として提供されています。これらのスニペットは、すべての条件で十分にテストされていません。ここに記載されているすべてのサンプル・コードは、いかなる保証も受けずにAS ISに提供されます。特定目的に対する非侵害、商品性、適合性の暗黙の保証は明示的に免責されます。

  1. エディタを開き、これらのPythonライブラリをインポートします。例:
    import requests 
    from requests.auth import HTTPBasicAuth
    import csv
    import json
    import Config
    import getpass
    
  2. CSVファイルを読み取って2つの変数を宣言する関数を作成します。カンマ区切り文字で区切られたCSVファイルを読み取るreaderオブジェクトと、ユーザーにプロンプトが表示されたときにユーザー資格証明を格納するpasswdオブジェクトです。
    def csv_dict_reader(file_obj):    
        
        reader = csv.DictReader(file_obj, delimiter=',')
        passwd = getpass.getpass('Password for APIPCS user- ({}) :'.format(Config.user))
    
  3. Inside the function, create a for loop to read each line in the CSV file and make the REST calls to create the APIs in Oracle API Platform Cloud Service.
        for line in reader:  
            print ('#############################################################################################################################')
            data = Config.api_create_json_str % (line["API_NAME"],line["API_NAME"],line["API_VERSION"], line["API_DESCRIPTION"],line["API_URI"],line["SERVICE_URL"])
            apipres=""        
            print ("data \n" + data + "\n")
            print ("Start Processing API: "+line["API_NAME"])
            try:
                apipres = requests.post(Config.createAPI_REST, data=data, auth=HTTPBasicAuth(Config.user,passwd),headers=Config.headers)               
            except Exception as e:
                print ("Exception while processing API \n"+str(e))
            
            print ("Response Status_code: "+ str(apipres.status_code)  )
            print ("Response Content: "+ str(apipres.content) )
            
            if apipres.status_code==201:          
                apiId=json.loads(apipres.content)["id"]
                print("API "+line["API_NAME"]+" created successfully with ID: "+apiId)
  4. GATEWAY_ID列の値を格納して、それらのAPIをデプロイする必要があるかどうかを判断し、GATEWAY_IDを含むAPIをデプロイします。
                
                gwid=line["GATEWAY_ID"]
                if gwid!="NONE":
                   print ("\nStart Deploying API: "+line["API_NAME"]+" To gateway: " +gwid)
                   deployReq=Config.gw_deploy_json_str % (gwid)
                   deployURL = Config.deployAPI_REST % (apiId)               
                   
                   try:
                       gwres = requests.post(deployURL, data=deployReq, auth=HTTPBasicAuth(Config.user,passwd),headers=Config.headers)               
                   except Exception as e:
                       print ("Exception while deploying API \n"+str(e))
                       
                   print ("Gateway deployment Response Status_code: "+ str(gwres.status_code)  )
                   print ("Gateway deployment Response Content: "+ str(gwres.content) )
                   
                   if gwres.status_code==201:
                       print ("api deployed successfully")
                   else:
                       print ("api deployment failed")
            
            print ('############################################################################################################################## \n')
  5. 関数をコールし、Config.pyファイルからパラメータとしてファイル名を渡します
    if __name__ == "__main__":
        with open(Config.api_file_name) as f_obj:
            csv_dict_reader(f_obj)    
  6. PythonファイルをLoadAPIs.pyとして保存します