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 웹 서비스에 대한 요청 페이로드로 사용되는 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 Gateway 변수를 선언합니다. 이러한 변수는 기본 클라이언트 스크립트에서 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에 업로드할 수 있습니다.

다음 코드 조각은 설명을 위해서만 제공됩니다. 이러한 스니펫은 모든 조건에서 철저하게 테스트되지 않았습니다. 여기에 포함된 모든 샘플 코드는 어떠한 보증도 없이 있는 그대로 제공됩니다. 특정 목적에 대한 비침해, 상품성 및 적합성에 대한 암시적 보증은 명시적으로 부인됩니다.

  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. 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으로 저장합니다.