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. 在文件中,输入这六个字段作为列。
    • 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 Portal 变量。在主客户端脚本中使用这些变量来创建 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 中。

以下代码段仅供说明。这些片段没有在所有条件下经过彻底测试。此处包含的所有示例代码均按 IS 提供,不作任何种类的担保。未侵权、适销性和特定用途的适用性隐含保证明示不予接受。

  1. 打开编辑器并导入这些 Python 库。例如:
    import requests 
    from requests.auth import HTTPBasicAuth
    import csv
    import json
    import Config
    import getpass
    
  2. 创建一个函数以读取 CSV 文件并声明两个变量:一个 reader 对象,用于读取用逗号分隔符分隔的 CSV 文件,另一个用于在提示用户时存储用户凭证的 passwd 对象。
    def csv_dict_reader(file_obj):    
        
        reader = csv.DictReader(file_obj, delimiter=',')
        passwd = getpass.getpass('Password for APIPCS user- ({}) :'.format(Config.user))
    
  3. 在函数内,创建 for 循环以读取 CSV 文件中的每一行,并进行 REST 调用以在 Oracle API Platform Cloud Service 中创建 API。
        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