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.

For example, the full URL would be: https://YOUR-API-PCS-INSTANCE-URL/apiplatform/management/v1/apis.

Create an API Data File

You can create a computer parsable data file, such as a comma separated file (CSV) to define the APIs that you want to upload in the Oracle API Platform Cloud Service portal.

Before you publish your APIs to Oracle API Platform Cloud Service, it is useful to have a data file where you can define and verify all the information such as APIs, naming conventions, descriptions, and back-end URLs.

Create a CSV Data File

A CSV file is a convenient way to create an API data file because you can list all the API fields as the columns and add the values in the rows.

To create a CSV template file:

  1. Open a text editor, or a spreadsheet software to add the details of the APIs that you want to upload to the Oracle API Platform Cloud Service API portal.
  2. In the file, enter these six fields as columns.
    • API_NAME: Provide a name for the API that you want to create. Each API should have a unique name.
    • API_VERSION: Provide the version of the API that you want to create.
    • API_DESCRIPTION: Provide a detailed description of the API.
    • API_URI: Provide the endpoint URL for the API. This is appended to the Gateway URL. Each API should have a unique URI.
    • SERVICE_URL: Back-end service URL that is invoked when the API receives a request.
    • GATEWAY_ID: Provide a gateway ID only if you want to deploy the API to the gateway. Otherwise, provide the value NONE. If the NONE value is provided the API will not be deployed.

    Don't leave any blank values int the CSV template file to avoid parsing errors or corrupting the file.

  3. Save the file.

Create a Configuration File

You can create a configuration file that stores your connection details, such as your user name, the REST endpoints URLs, and a JSON template that is used as a request payload to the REST web services.

To create a configuration file:

  1. Open your editor and declare the common variables:
    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. Declare the API Portal variables. These variables are used in the main client script to create the APIs.
    ## 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. Declare the API Gateway variables. These variables are used in the main client script to deploy the APIs.
    ## API Gateway variables
    
    deployAPI_REST = apip_url+'/management/v1/apis/%s/deployments'        
    gw_deploy_json_str = '''{"gatewayId":"%s","action":"DEPLOY","description":"","runtimeState":"ACTIVE"}'''
    
  4. Save your file as Config.py.

Create a REST Client with Python

You can develop a simple REST client using the Python programming language to upload APIs into Oracle API Platform Cloud Service.

The following snippets of code are provided for illustrative purposes only. These snippets have not been thoroughly tested under all conditions. All sample code contained herein are provided to you AS IS without any warranties of any kind. The implied warranties of non-infringement, merchantability and fitness for a particular purpose are expressly disclaimed.

  1. Open an editor and import these Python libraries. For example:
    import requests 
    from requests.auth import HTTPBasicAuth
    import csv
    import json
    import Config
    import getpass
    
  2. Create a function to read the CSV file and declare two variables, a reader object to read the CSV file that is separated by the comma delimeter, and a passwd object to store the user credentials when the user is prompted.
    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. Store the value of the GATEWAY_ID column to determine if those APIs will need to be deployed, and deploy the APIs that contain a GATEWAY_ID.
                
                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. Call the function and pass the file name from the Config.py file as parameter
    if __name__ == "__main__":
        with open(Config.api_file_name) as f_obj:
            csv_dict_reader(f_obj)    
  6. Save the Python file as LoadAPIs.py