You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@openwhisk.apache.org by GitBox <gi...@apache.org> on 2018/01/18 21:52:18 UTC

[GitHub] dubeejw closed pull request #2966: Path parameter support for API GW

dubeejw closed pull request #2966: Path parameter support for API GW
URL: https://github.com/apache/incubator-openwhisk/pull/2966
 
 
   

This is a PR merged from a forked repository.
As GitHub hides the original diff on merge, it is displayed below for
the sake of provenance:

As this is a foreign pull request (from a fork), the diff is supplied
below (as it won't show otherwise due to GitHub magic):

diff --git a/ansible/group_vars/all b/ansible/group_vars/all
index 7cb11556f6..92b047ed1e 100644
--- a/ansible/group_vars/all
+++ b/ansible/group_vars/all
@@ -185,7 +185,7 @@ apigateway:
     api: 9000
     api_secure: 443
     mgmt: 9001
-  version: 0.8.2
+  version: 0.9.8
 
 redis:
   version: 3.2
diff --git a/core/routemgmt/common/apigw-utils.js b/core/routemgmt/common/apigw-utils.js
index c78f4c80b9..cb605ca637 100644
--- a/core/routemgmt/common/apigw-utils.js
+++ b/core/routemgmt/common/apigw-utils.js
@@ -24,6 +24,148 @@ var _ = require('lodash');
 const ApimgmtUserAgent = "OpenWhisk-apimgmt/1.0.0";
 var UserAgent = ApimgmtUserAgent;
 
+/**
+ * Helper method for the validateFinalSwagger function. Generates a map of operationId to target-url strings so we
+ * can validate that each operationId we find that has a parameter in the path also has its target-url appended with
+ * $(request.path)
+ *
+ * @param ibmConfig   Required. The 'x-ibm-configuration' portion of the swaggerApi.
+ * @return A map of operationId->target-url pairs for checking.
+ */
+function generateTargetUrlMap(ibmConfig) {
+  var targetUrls = {};
+  ibmConfig['assembly']['execute'].forEach(function(exec) {
+    if (exec['operation-switch'] && exec['operation-switch']['case']) {
+      exec['operation-switch']['case'].forEach(function(element) {
+        var operations = element['operations'];
+        var execs = element['execute'];
+        //each nth element of execs and operations go together, so lets add those to the map.
+        for (var i = 0; i < operations.length ; ++i) {
+          if(i < execs.length && execs[i] && execs[i]['invoke']['target-url']) {
+            targetUrls[operations[i]] = execs[i]['invoke']['target-url'];
+          }
+        }
+      });
+    }
+  });
+  return targetUrls;
+}
+
+/**
+ * Helper function that just validates whether a relative path meets the following conditions:
+ * 1. It has not path parameters
+ * 2. If it has path parameters, that the parameters are well formed (i.e. each param is surrounded by {}).
+ *
+ * @param relativePath   Required. The relative path we are checking.
+ * @return True if the path is valid, false otherwise.
+ */
+function isValidRelativePath(relativePath) {
+  var validParamRegex = /\/\{([^\/]+)\}\/|\/\{([^\/]+)\}$/g;
+  if (relativePath.match(validParamRegex)) {
+    return true;
+  }
+  return false;
+}
+
+/**
+ * Simple function to get the name of each path parameter defined in the path.
+ *
+ * @param path   Required. The path we are checking.
+ * @return An array that contains each named path parameter, or an empty list if none are found.
+ */
+function getPathParameters(relativePath) {
+  var params = [];
+  var validNameRegex = /\{([^\/]+)\}/g
+  //Match returns all the matches found, including the {} chars. so we have to remove them.
+  var namesFound = relativePath.match(validNameRegex);
+  if (namesFound) {
+    params = namesFound.map(function (pathName){
+      return pathName.substring(1,pathName.length-1);
+    });
+  }
+  return params;
+}
+
+/**
+ * Currently this only checks the final swagger that will be passed into API GW whether the path parameter definition
+ * is correct.
+ *
+ * @param swaggerApi   Required. The API swagger object to send to the API gateway
+ * @return A promise with the fully validated swaggerApi, or an error response if rejected.
+ */
+function validateFinalSwagger(swaggerApi) {
+  return new Promise(function(resolve, reject) {
+    // This returns a map of urls to check for path parameters.
+    console.log("validateFinalSwagger: Validating swapper before posting to API GW.")
+    var errorMsg;
+    var paths = swaggerApi['paths'];
+
+    if (swaggerApi.basePath && isValidRelativePath(swaggerApi.basePath)) {
+      errorMsg = "The base path (" + swaggerApi.basePath + ") cannot have parameters. Only the relative path supports path parameters.";
+    }
+    /*
+     * This code will look at each path defined, and look at all the parameters in each path, and validate that each
+     * verb (GET,POST, etc) for each path defines parameter objects for each parameter defined in the path. For each of
+     * these that contain parameters, it will also check that its target-url ends in $(request.path).
+     * #beginPathValidation
+     */
+    var targetUrlMap = generateTargetUrlMap(swaggerApi['x-ibm-configuration']);
+    for (var key in paths) {
+      if (errorMsg) { break; }
+      var idx = 0;
+      if (isValidRelativePath(key)) {
+        //Path is valid, lets check that we have parameters defined for each path parameter and that the target-url
+        //has $(request.path) at the end.
+        var namedParamsInPath = getPathParameters(key);
+        //Loop over each verb (GET,POST,etc), each should contain path parameters.
+        var parameters = paths[key]['parameters'] ? paths[key]['parameters'] : [];
+        for (var httpType in paths[key]) {
+          if (httpType == "parameters") {
+            continue;
+          }
+          var xOpenWhisk = paths[key][httpType]['x-openwhisk']
+          if (xOpenWhisk && xOpenWhisk['url'] && !xOpenWhisk['url'].endsWith('.http')) {
+            errorMsg = "The action must use a response type of '.http' in order to receive the path parameters.";
+            break;
+          }
+          var opId = paths[key][httpType].operationId;
+          if (targetUrlMap[opId] && !targetUrlMap[opId].endsWith('.http$(request.path)')) {
+            errorMsg = "The target-url for operationId '" + opId;
+            errorMsg += "' must end in '$(request.path)' in order for actions to receive the path parameters.";
+            break;
+          }
+          var allParams = parameters.concat(paths[key][httpType].parameters);
+          for (var i = 0 ; i < namedParamsInPath.length ; ++i) {
+            var found = false;
+            for (var j in allParams) {
+              if (allParams[j].name == namedParamsInPath[i]) {
+                found = true;
+                break;
+              }
+            }
+            if (!found) {
+              errorMsg = "The parameter '" + namedParamsInPath[i] + "' defined in path '" + key + "' does not match any";
+              errorMsg += " of the parameters defined for the path in the swagger file.";
+              break;
+            }
+          }
+          if(errorMsg) { break; }
+        }
+        if(errorMsg) { break; }
+      }
+    }
+    //#endPathValidation
+    if (errorMsg) {
+      console.error("validateFinalSwagger:" + errorMsg)
+      reject(errorMsg);
+    } else {
+      console.log("validateFinalSwagger: Validation of swagger before posting to API GW was successful.")
+      resolve(swaggerApi);
+    }
+  });
+}
+
+
 /**
  * Configures an API route on the API Gateway.  This API will map to an OpenWhisk action that
  * will be invoked by the API Gateway when the API route is accessed.
@@ -41,25 +183,25 @@ function addApiToGateway(gwInfo, spaceGuid, swaggerApi, apiId) {
 
   console.log('addApiToGateway: ');
   try {
-  var options = {
-    followAllRedirects: true,
-    url: gwInfo.gwUrl+'/'+encodeURIComponent(spaceGuid) + '/apis',
-    json: swaggerApi,  // Use of json automatically sets header: 'Content-Type': 'application/json'
-    headers: {
-      'User-Agent': UserAgent
+    var options = {
+      followAllRedirects: true,
+      url: gwInfo.gwUrl+'/'+encodeURIComponent(spaceGuid) + '/apis',
+      json: swaggerApi,  // Use of json automatically sets header: 'Content-Type': 'application/json'
+      headers: {
+        'User-Agent': UserAgent
+      }
+    };
+    if (gwInfo.gwAuth) {
+      _.set(options, "headers.Authorization", 'Bearer ' + gwInfo.gwAuth);
     }
-  };
-  if (gwInfo.gwAuth) {
-    _.set(options, "headers.Authorization", 'Bearer ' + gwInfo.gwAuth);
-  }
 
-  if (apiId) {
-    console.log("addApiToGateway: Updating existing API");
-    options.url = gwInfo.gwUrl + '/' + encodeURIComponent(spaceGuid) + '/apis/' + encodeURIComponent(apiId);
-    requestFcn = request.put;
-  }
+    if (apiId) {
+      console.log("addApiToGateway: Updating existing API");
+      options.url = gwInfo.gwUrl + '/' + encodeURIComponent(spaceGuid) + '/apis/' + encodeURIComponent(apiId);
+      requestFcn = request.put;
+    }
 
-  console.log('addApiToGateway: request: '+JSON.stringify(options, " ", 2));
+    console.log('addApiToGateway: request: '+JSON.stringify(options, " ", 2));
   }
   catch (e) {
     console.error('addApiToGateway exception: '+e);
@@ -392,9 +534,9 @@ function addEndpointToSwaggerApi(swaggerApi, endpoint, responsetype) {
     if (!swaggerApi.paths[endpoint.gatewayPath]) {
       swaggerApi.paths[endpoint.gatewayPath] = {};
     }
-
     swaggerApi.paths[endpoint.gatewayPath][operation] = {
       'operationId': operationId,
+      'parameters': endpoint.pathParameters,
       'x-openwhisk': {
         'url': makeWebActionBackendUrl(endpoint.action, responsetype),
         'namespace': endpoint.action.namespace,
@@ -425,7 +567,7 @@ function setActionOperationInvocationDetails(swagger, endpoint, operationId, res
   var caseIdx = getCaseOperationIdx(caseArr, operationId);
   var operations = [operationId];
   _.set(swagger, 'x-ibm-configuration.assembly.execute[0].operation-switch.case['+caseIdx+'].operations', operations);
-  _.set(swagger, 'x-ibm-configuration.assembly.execute[0].operation-switch.case['+caseIdx+'].execute[0].invoke.target-url',  makeWebActionBackendUrl(endpoint.action, responsetype));
+  _.set(swagger, 'x-ibm-configuration.assembly.execute[0].operation-switch.case['+caseIdx+'].execute[0].invoke.target-url',  makeWebActionBackendUrl(endpoint.action, responsetype, getPathParameters(endpoint.gatewayPath)));
   _.set(swagger, 'x-ibm-configuration.assembly.execute[0].operation-switch.case['+caseIdx+'].execute[0].invoke.verb', 'keep');
 }
 
@@ -451,14 +593,16 @@ function getCaseOperationIdx(caseArr, operationId) {
 // Parameters
 //   endpointAction       - fully qualified action name (i.e. /ns/pkg/action or /ns/action)
 //   endpointResponseType - determines the action invocation extension without the '.' (i.e. http, json, etc)
+//   parameters           - the parameters defined in the path, if any.
 // Returns:
 //   string               - web-action URL
-function makeWebActionBackendUrl(endpointAction, endpointResponseType) {
+function makeWebActionBackendUrl(endpointAction, endpointResponseType, parameters) {
   host = getHostFromActionUrl(endpointAction.backendUrl);
   ns = endpointAction.namespace;
   pkg = getPackageNameFromFqActionName(endpointAction.name) || 'default';
   name = getActionNameFromFqActionName(endpointAction.name);
-  return 'https://' + host + '/api/v1/web/' + ns + '/' + pkg + '/' + name + '.' + endpointResponseType;
+  reqPath = parameters != null && parameters.length > 0 ? "$(request.path)" : "";
+  return 'https://' + host + '/api/v1/web/' + ns + '/' + pkg + '/' + name + '.' + endpointResponseType + reqPath;
 }
 
 /*
@@ -829,7 +973,11 @@ function makeResponseObject(resp, isWebAction) {
  */
 function makeJsonString(x) {
   // If the value is not already a string, rely on JSON.stringify to convert it correctly
-  if (typeof x != 'string') {
+  if (x instanceof Error) {
+    //Print the whole error here as we are only returning the error message and nothing else.
+    console.error(x);
+    return JSON.stringify(x.message);
+  } else if (typeof x != 'string') {
     try {
       return JSON.stringify(x);
     } catch (e) {
@@ -894,3 +1042,4 @@ module.exports.makeErrorResponseObject = makeErrorResponseObject;
 module.exports.makeResponseObject = makeResponseObject;
 module.exports.makeJsonString = makeJsonString;
 module.exports.setSubUserAgent = setSubUserAgent;
+module.exports.validateFinalSwagger = validateFinalSwagger;
diff --git a/core/routemgmt/createApi/createApi.js b/core/routemgmt/createApi/createApi.js
index a984b33f6f..fbe83be7fd 100644
--- a/core/routemgmt/createApi/createApi.js
+++ b/core/routemgmt/createApi/createApi.js
@@ -154,6 +154,10 @@ function main(message) {
         return Promise.resolve(utils2.addEndpointToSwaggerApi(endpointDoc, doc, message.responsetype));
       }
     })
+    .then(function(apiSwagger){
+      console.log("Validating Swagger doc before sending it to API GW.")
+      return utils2.validateFinalSwagger(apiSwagger);
+    })
     .then(function(apiSwagger) {
       console.log('Final swagger API config: '+ JSON.stringify(apiSwagger));
       return utils2.addApiToGateway(gwInfo, message.spaceguid, apiSwagger, apiDocId);
@@ -207,6 +211,10 @@ function main(message) {
         return Promise.resolve(utils.addEndpointToSwaggerApi(swaggerApi, doc));
       }
     })
+    .then(function(apiSwagger){
+       console.log("Validating Swagger doc before sending it to API GW.")
+       return utils2.validateFinalSwagger(apiSwagger);
+    })
     .then(function(swaggerApi) {
       console.log('Final swagger API config: '+ JSON.stringify(swaggerApi));
       return utils.addApiToGateway(gwInfo, tenantId, swaggerApi, gwApiId);
diff --git a/tests/dat/apigw/apigw_path_param_support_test_invalidActionType.json b/tests/dat/apigw/apigw_path_param_support_test_invalidActionType.json
new file mode 100644
index 0000000000..f7edfe9047
--- /dev/null
+++ b/tests/dat/apigw/apigw_path_param_support_test_invalidActionType.json
@@ -0,0 +1,62 @@
+{
+  "swagger": "2.0",
+  "basePath": "/guest/v1",
+  "info": {
+    "title": "/guest/v1",
+    "version": "1.0.0"
+  },
+  "paths": {
+    "/api2/greeting2/{name}": {
+      "get": {
+        "operationId": "getApi2Greeting2Name",
+        "parameters": [
+          {
+            "in": "path",
+            "name": "name",
+            "type": "string",
+            "required": true
+          }
+        ],
+        "responses": {
+          "default": {
+            "description": "Default response"
+          }
+        },
+        "x-openwhisk": {
+          "action": "testapi",
+          "namespace": "guest",
+          "package": "",
+          "url": "https://127.0.0.1/api/v1/web/guest/default/testapi.json"
+        }
+      }
+    }
+  },
+  "x-ibm-configuration": {
+    "assembly": {
+      "execute": [
+        {
+          "operation-switch": {
+            "case": [
+              {
+                "execute": [
+                  {
+                    "invoke": {
+                      "target-url": "https://127.0.0.1/api/v1/web/guest/default/testapi.json$(request.path)",
+                      "verb": "keep"
+                    }
+                  }
+                ],
+                "operations": [
+                  "getApi2Greeting2Name"
+                ]
+              }
+            ]
+          }
+        }
+      ]
+    },
+    "cors": {
+      "enabled": true
+    }
+  }
+}
\ No newline at end of file
diff --git a/tests/dat/apigw/apigw_path_param_support_test_invalidParamName1.json b/tests/dat/apigw/apigw_path_param_support_test_invalidParamName1.json
new file mode 100644
index 0000000000..39b7c943f2
--- /dev/null
+++ b/tests/dat/apigw/apigw_path_param_support_test_invalidParamName1.json
@@ -0,0 +1,62 @@
+{
+  "swagger": "2.0",
+  "basePath": "/guest/v1",
+  "info": {
+    "title": "/guest/v1",
+    "version": "1.0.0"
+  },
+  "paths": {
+    "/api2/greeting2/{name}": {
+      "get": {
+        "operationId": "getApi2Greeting2Name",
+        "parameters": [
+          {
+            "in": "path",
+            "name": "name1",
+            "type": "string",
+            "required": true
+          }
+        ],
+        "responses": {
+          "default": {
+            "description": "Default response"
+          }
+        },
+        "x-openwhisk": {
+          "action": "testapi",
+          "namespace": "guest",
+          "package": "",
+          "url": "https://127.0.0.1/api/v1/web/guest/default/testapi.http"
+        }
+      }
+    }
+  },
+  "x-ibm-configuration": {
+    "assembly": {
+      "execute": [
+        {
+          "operation-switch": {
+            "case": [
+              {
+                "execute": [
+                  {
+                    "invoke": {
+                      "target-url": "https://127.0.0.1/api/v1/web/guest/default/testapi.http$(request.path)",
+                      "verb": "keep"
+                    }
+                  }
+                ],
+                "operations": [
+                  "getApi2Greeting2Name"
+                ]
+              }
+            ]
+          }
+        }
+      ]
+    },
+    "cors": {
+      "enabled": true
+    }
+  }
+}
\ No newline at end of file
diff --git a/tests/dat/apigw/apigw_path_param_support_test_invalidParamName2.json b/tests/dat/apigw/apigw_path_param_support_test_invalidParamName2.json
new file mode 100644
index 0000000000..353429daf0
--- /dev/null
+++ b/tests/dat/apigw/apigw_path_param_support_test_invalidParamName2.json
@@ -0,0 +1,62 @@
+{
+  "swagger": "2.0",
+  "basePath": "/guest/v1",
+  "info": {
+    "title": "/guest/v1",
+    "version": "1.0.0"
+  },
+  "paths": {
+    "/api2/greeting2/{name}/{id}": {
+      "get": {
+        "operationId": "getApi2Greeting2Name",
+        "parameters": [
+          {
+            "in": "path",
+            "name": "name",
+            "type": "string",
+            "required": true
+          }
+        ],
+        "responses": {
+          "default": {
+            "description": "Default response"
+          }
+        },
+        "x-openwhisk": {
+          "action": "testapi",
+          "namespace": "guest",
+          "package": "",
+          "url": "https://127.0.0.1/api/v1/web/guest/default/testapi.http"
+        }
+      }
+    }
+  },
+  "x-ibm-configuration": {
+    "assembly": {
+      "execute": [
+        {
+          "operation-switch": {
+            "case": [
+              {
+                "execute": [
+                  {
+                    "invoke": {
+                      "target-url": "https://127.0.0.1/api/v1/web/guest/default/testapi.http$(request.path)",
+                      "verb": "keep"
+                    }
+                  }
+                ],
+                "operations": [
+                  "getApi2Greeting2Name"
+                ]
+              }
+            ]
+          }
+        }
+      ]
+    },
+    "cors": {
+      "enabled": true
+    }
+  }
+}
\ No newline at end of file
diff --git a/tests/dat/apigw/apigw_path_param_support_test_invalidTargetUrl.json b/tests/dat/apigw/apigw_path_param_support_test_invalidTargetUrl.json
new file mode 100644
index 0000000000..821062d1d1
--- /dev/null
+++ b/tests/dat/apigw/apigw_path_param_support_test_invalidTargetUrl.json
@@ -0,0 +1,62 @@
+{
+  "swagger": "2.0",
+  "basePath": "/guest/v1",
+  "info": {
+    "title": "/guest/v1",
+    "version": "1.0.0"
+  },
+  "paths": {
+    "/api2/greeting2/{name}": {
+      "get": {
+        "operationId": "getApi2Greeting2Name",
+        "parameters": [
+          {
+            "in": "path",
+            "name": "name",
+            "type": "string",
+            "required": true
+          }
+        ],
+        "responses": {
+          "default": {
+            "description": "Default response"
+          }
+        },
+        "x-openwhisk": {
+          "action": "testapi",
+          "namespace": "guest",
+          "package": "",
+          "url": "https://127.0.0.1/api/v1/web/guest/default/testapi.http"
+        }
+      }
+    }
+  },
+  "x-ibm-configuration": {
+    "assembly": {
+      "execute": [
+        {
+          "operation-switch": {
+            "case": [
+              {
+                "execute": [
+                  {
+                    "invoke": {
+                      "target-url": "https://127.0.0.1/api/v1/web/guest/default/testapi.http",
+                      "verb": "keep"
+                    }
+                  }
+                ],
+                "operations": [
+                  "getApi2Greeting2Name"
+                ]
+              }
+            ]
+          }
+        }
+      ]
+    },
+    "cors": {
+      "enabled": true
+    }
+  }
+}
\ No newline at end of file
diff --git a/tests/dat/apigw/apigw_path_param_support_test_withPathParameters1.json b/tests/dat/apigw/apigw_path_param_support_test_withPathParameters1.json
new file mode 100644
index 0000000000..104f3c6d73
--- /dev/null
+++ b/tests/dat/apigw/apigw_path_param_support_test_withPathParameters1.json
@@ -0,0 +1,62 @@
+{
+  "swagger": "2.0",
+  "basePath": "/guest/v1",
+  "info": {
+    "title": "/guest/v1",
+    "version": "1.0.0"
+  },
+  "paths": {
+    "/api2/greeting2/{name}": {
+      "get": {
+        "operationId": "getApi2Greeting2Name",
+        "parameters": [
+          {
+            "in": "path",
+            "name": "name",
+            "type": "string",
+            "required": true
+          }
+        ],
+        "responses": {
+          "default": {
+            "description": "Default response"
+          }
+        },
+        "x-openwhisk": {
+          "action": "cli_apigwtest_path_param_swagger_action",
+          "namespace": "%NAMESPACE%",
+          "package": "",
+          "url": "%HOST%/api/v1/web/%NAMESPACE%/default/cli_apigwtest_path_param_swagger_action.http"
+        }
+      }
+    }
+  },
+  "x-ibm-configuration": {
+    "assembly": {
+      "execute": [
+        {
+          "operation-switch": {
+            "case": [
+              {
+                "execute": [
+                  {
+                    "invoke": {
+                      "target-url": "%HOST%/api/v1/web/%NAMESPACE%/default/cli_apigwtest_path_param_swagger_action.http$(request.path)",
+                      "verb": "keep"
+                    }
+                  }
+                ],
+                "operations": [
+                  "getApi2Greeting2Name"
+                ]
+              }
+            ]
+          }
+        }
+      ]
+    },
+    "cors": {
+      "enabled": true
+    }
+  }
+}
\ No newline at end of file
diff --git a/tests/dat/apigw/apigw_path_param_support_test_withPathParameters2.json b/tests/dat/apigw/apigw_path_param_support_test_withPathParameters2.json
new file mode 100644
index 0000000000..a09aeea6ba
--- /dev/null
+++ b/tests/dat/apigw/apigw_path_param_support_test_withPathParameters2.json
@@ -0,0 +1,70 @@
+{
+  "swagger": "2.0",
+  "basePath": "/guest/v1",
+  "info": {
+    "title": "/guest/v1",
+    "version": "1.0.0"
+  },
+  "paths": {
+    "/api2/greeting2/{name}/{something}": {
+      "get": {
+        "operationId": "getApi2Greeting2Name",
+        "parameters": [
+          {
+            "in": "path",
+            "name": "name",
+            "type": "string",
+            "required": true
+          }
+        ],
+        "responses": {
+          "default": {
+            "description": "Default response"
+          }
+        },
+        "x-openwhisk": {
+          "action": "cli_apigwtest_path_param_swagger_action",
+          "namespace": "guest",
+          "package": "",
+          "url": "%HOST%/api/v1/web/guest/default/cli_apigwtest_path_param_swagger_action.http"
+        }
+      },
+      "parameters": [
+        {
+          "in": "path",
+          "name": "something",
+          "type": "string",
+          "required": true
+        }
+      ]
+    }
+  },
+  "x-ibm-configuration": {
+    "assembly": {
+      "execute": [
+        {
+          "operation-switch": {
+            "case": [
+              {
+                "execute": [
+                  {
+                    "invoke": {
+                      "target-url": "%HOST%/api/v1/web/guest/default/cli_apigwtest_path_param_swagger_action.http$(request.path)",
+                      "verb": "keep"
+                    }
+                  }
+                ],
+                "operations": [
+                  "getApi2Greeting2Name"
+                ]
+              }
+            ]
+          }
+        }
+      ]
+    },
+    "cors": {
+      "enabled": true
+    }
+  }
+}
\ No newline at end of file
diff --git a/tests/src/test/scala/whisk/core/cli/test/ApiGwRestTests.scala b/tests/src/test/scala/whisk/core/cli/test/ApiGwRestTests.scala
index 88099537f8..3fb8d2da17 100644
--- a/tests/src/test/scala/whisk/core/cli/test/ApiGwRestTests.scala
+++ b/tests/src/test/scala/whisk/core/cli/test/ApiGwRestTests.scala
@@ -18,20 +18,22 @@
 package whisk.core.cli.test
 
 import akka.http.scaladsl.model.StatusCodes.OK
-
 import org.junit.runner.RunWith
 import org.scalatest.junit.JUnitRunner
 import spray.json.JsObject
-
+import spray.json._
 import common.rest.WskRest
 import common.rest.RestResult
-import common.TestUtils.RunResult
+import common.TestUtils.{RunResult, _}
+import common.TestUtils
+import system.rest.RestUtil
+import java.io.File
 
 /**
  * Tests for testing the CLI "api" subcommand.  Most of these tests require a deployed backend.
  */
 @RunWith(classOf[JUnitRunner])
-class ApiGwRestTests extends ApiGwTests {
+class ApiGwRestTests extends ApiGwTests with RestUtil {
   override lazy val wsk = new WskRest
   override lazy val createCode = OK.intValue
 
@@ -245,4 +247,59 @@ class ApiGwRestTests extends ApiGwTests {
     rr.stderr should include("A valid auth key is required")
   }
 
+  def getSwaggerApiUrl(rr: RunResult): String = {
+    val apiResultRest = rr.asInstanceOf[RestResult]
+    return apiResultRest.getField("gwApiUrl") + "/path"
+  }
+
+  def getParametersFromJson(rr: RunResult, pathName: String): Vector[JsObject] = {
+    val apiResult = rr.asInstanceOf[RestResult]
+    val apidoc = apiResult.getFieldJsObject("apidoc")
+    val paths = RestResult.getFieldJsObject(apidoc, "paths")
+    val path = RestResult.getFieldJsObject(paths, pathName)
+    val get = RestResult.getFieldJsObject(path, "get")
+    RestResult.getFieldListJsObject(get, "parameters")
+  }
+
+  behavior of "Wsk rest api creation with path parameters with swagger"
+
+  it should "create the API when swagger file contains path parameters" in withAssetCleaner(wskprops) {
+    (wp, assetHelper) =>
+      println(wskprops.apihost)
+      val actionName = "cli_apigwtest_path_param_swagger_action"
+      var exception: Throwable = null
+      val apiName = "/guest/v1"
+      val reqPath = "\\$\\(request.path\\)"
+      val testRelPath = "/api2/greeting2/{name}"
+      val testRelPathGet = "/api2/greeting2/name"
+      val hostRegex = "%HOST%".r
+      val namespaceRegex = "%NAMESPACE%".r
+      var file = TestUtils.getTestActionFilename(s"echo-web-http.js")
+      assetHelper.withCleaner(wsk.action, actionName, confirmDelete = true) { (action, _) =>
+        action.create(actionName, Some(file), web = Some("true"))
+      }
+      try {
+        val apiGwURL = "https://" + wskprops.apihost
+        file = TestUtils.getTestApiGwFilename("apigw_path_param_support_test_withPathParameters1.json")
+        var replacements = Map(hostRegex -> apiGwURL, namespaceRegex -> "guest")
+        file = replaceStringInFile(file, replacements)
+        var rr = apiCreate(swagger = Some(file), expectedExitCode = SUCCESS_EXIT)
+        val apiResult = rr.asInstanceOf[RestResult]
+        val url = apiResult.getField("gwApiUrl")
+        val params = getParametersFromJson(rr, testRelPath)
+        println("url: " + url)
+        params.size should be(1)
+        RestResult.getField(params(0), "name") should be("name")
+        RestResult.getField(params(0), "in") should be("path")
+        RestResult.getFieldJsValue(params(0), "required").toString() should be("true")
+        RestResult.getField(params(0), "type") should be("string")
+      } catch {
+        case unknown: Throwable => exception = unknown;
+      } finally {
+        apiDelete(basepathOrApiName = apiName)
+        val f = new File(file)
+        if (f.exists()) { f.delete() }
+      }
+      assert(exception == null)
+  }
 }
diff --git a/tests/src/test/scala/whisk/core/cli/test/ApiGwTests.scala b/tests/src/test/scala/whisk/core/cli/test/ApiGwTests.scala
index 145ea6bb00..ed74c9ac9d 100644
--- a/tests/src/test/scala/whisk/core/cli/test/ApiGwTests.scala
+++ b/tests/src/test/scala/whisk/core/cli/test/ApiGwTests.scala
@@ -22,11 +22,12 @@ import java.io.BufferedWriter
 import java.io.FileWriter
 
 import org.junit.runner.RunWith
-
 import org.scalatest.junit.JUnitRunner
-
+import org.apache.commons.io.FileUtils
 import common.TestUtils._
 import common.TestUtils
+
+import scala.util.matching.Regex
 import common.WskProps
 
 /**
@@ -163,6 +164,67 @@ abstract class ApiGwTests extends BaseApiGwTests {
     rr.stderr should include("The supplied authentication is invalid")
   }
 
+  def replaceStringInFile(fileName: String, replacements: Map[Regex, String]): String = {
+    val encoding = "UTF-8"
+
+    val contents = FileUtils.readFileToString(new File(fileName), encoding)
+    var newContents = contents
+    replacements foreach ((regex) => newContents = regex._1.replaceAllIn(newContents, regex._2))
+    val tmpFileName = fileName + "-" + System.currentTimeMillis() + ".tmp"
+    val tmpFile = new File(tmpFileName)
+    if (tmpFile.exists()) {
+      FileUtils.forceDelete(tmpFile)
+    }
+    FileUtils.writeStringToFile(new File(tmpFileName), newContents, encoding)
+    tmpFileName
+  }
+
+  behavior of "Wsk api creation with path parameters no swagger"
+
+  it should "fail to create an Api if the base path contains path parameters" in {
+    val badBasePath = "/bad/{path}/value"
+    var rr = apiCreate(
+      basepath = Some(badBasePath),
+      relpath = Some("/good/path"),
+      operation = Some("GET"),
+      action = Some("action"),
+      expectedExitCode = ANY_ERROR_EXIT)
+    rr.stderr should include(
+      s"The base path (${badBasePath}) cannot have parameters. Only the relative path supports path parameters.")
+  }
+
+  behavior of "Wsk api creation with path parameters using swagger"
+
+  it should "fail to create API when swagger file contains invalid action response type" in {
+    val file = TestUtils.getTestApiGwFilename("apigw_path_param_support_test_invalidActionType.json")
+    val rr = apiCreate(swagger = Some(file), expectedExitCode = ANY_ERROR_EXIT)
+    var errMsg =
+      "API creation failure: The action must use a response type of '.http' in order to receive the path parameters."
+    rr.stderr should include(errMsg)
+  }
+
+  it should "fail to create API when swagger file contains invalid parameter names" in {
+    var file = TestUtils.getTestApiGwFilename("apigw_path_param_support_test_invalidParamName1.json")
+    var rr = apiCreate(swagger = Some(file), expectedExitCode = ANY_ERROR_EXIT)
+    var errMsg =
+      "API creation failure: The parameter 'name' defined in path '%s' does not match any of the parameters defined for the path in the swagger file."
+    rr.stderr should include(errMsg.format("/api2/greeting2/{name}"))
+
+    file = TestUtils.getTestApiGwFilename("apigw_path_param_support_test_invalidParamName2.json")
+    rr = apiCreate(swagger = Some(file), expectedExitCode = ANY_ERROR_EXIT)
+    errMsg =
+      "API creation failure: The parameter 'id' defined in path '%s' does not match any of the parameters defined for the path in the swagger file."
+    rr.stderr should include(errMsg.format("/api2/greeting2/{name}/{id}"))
+  }
+
+  it should "fail to create API when swagger file contains an invalid target-url" in {
+    val file = TestUtils.getTestApiGwFilename("apigw_path_param_support_test_invalidTargetUrl.json")
+    val rr = apiCreate(swagger = Some(file), expectedExitCode = ANY_ERROR_EXIT)
+    var errMsg = "API creation failure: The target-url for operationId 'getApi2Greeting2Name' must "
+    errMsg += "end in '$(request.path)' in order for actions to receive the path parameters."
+    rr.stderr should include(errMsg)
+  }
+
   behavior of "Wsk api"
 
   it should "reject an api commands with an invalid path parameter" in {
@@ -271,7 +333,6 @@ abstract class ApiGwTests extends BaseApiGwTests {
     val testapiname = testName + " API Name"
     val actionName = testName + "_action"
     try {
-      println("cli namespace: " + clinamespace)
       // Create the action for the API.  It must be a "web-action" action.
       val file = TestUtils.getTestActionFilename(s"echo.js")
       wsk.action.create(name = actionName, artifact = Some(file), expectedExitCode = createCode, web = Some("true"))
@@ -282,14 +343,12 @@ abstract class ApiGwTests extends BaseApiGwTests {
         operation = Some(testurlop),
         action = Some(actionName),
         apiname = Some(testapiname))
-      println("api create: " + rr.stdout)
       verifyApiCreated(rr)
       rr = apiList(
         basepathOrApiName = Some(testbasepath),
         relpath = Some(testrelpath),
         operation = Some(testurlop),
         full = Some(true))
-      println("api list: " + rr.stdout)
       verifyApiList(rr, clinamespace, actionName, testurlop, testbasepath, testrelpath, testapiname)
     } finally {
       wsk.action.delete(name = actionName, expectedExitCode = DONTCARE_EXIT)
@@ -306,8 +365,6 @@ abstract class ApiGwTests extends BaseApiGwTests {
     val testapiname = testName + " API Name"
     val actionName = testName + "_action"
     try {
-      println("cli namespace: " + clinamespace)
-
       // Create the action for the API.  It must be a "web-action" action.
       val file = TestUtils.getTestActionFilename(s"echo.js")
       wsk.action.create(name = actionName, artifact = Some(file), expectedExitCode = createCode, web = Some("true"))
@@ -472,8 +529,6 @@ abstract class ApiGwTests extends BaseApiGwTests {
       var rr = apiCreate(swagger = Some(swaggerPath))
       verifyApiCreated(rr)
       rr = apiList(basepathOrApiName = Some(testbasepath), relpath = Some(testrelpath), operation = Some(testurlop))
-      println("list stdout: " + rr.stdout)
-      println("list stderr: " + rr.stderr)
       verifyApiFullList(rr, "", actionName, testurlop, testbasepath, testrelpath, testapiname)
 
     } finally {
@@ -566,8 +621,6 @@ abstract class ApiGwTests extends BaseApiGwTests {
     val testapiname = testName + " API Name"
     val actionName = testName + "a-c@t ion"
     try {
-      println("cli namespace: " + clinamespace)
-
       // Create the action for the API.  It must be a "web-action" action.
       val file = TestUtils.getTestActionFilename(s"echo.js")
       wsk.action.create(name = actionName, artifact = Some(file), expectedExitCode = createCode, web = Some("true"))
@@ -600,8 +653,6 @@ abstract class ApiGwTests extends BaseApiGwTests {
     val swaggerPath = TestUtils.getTestApiGwFilename(s"testswaggerdocinvalid")
     try {
       val rr = apiCreate(swagger = Some(swaggerPath), expectedExitCode = ANY_ERROR_EXIT)
-      println("api create stdout: " + rr.stdout)
-      println("api create stderr: " + rr.stderr)
       verifyInvalidSwagger(rr)
     } finally {
       apiDelete(basepathOrApiName = testbasepath, expectedExitCode = DONTCARE_EXIT)
@@ -699,8 +750,6 @@ abstract class ApiGwTests extends BaseApiGwTests {
     val swaggerPath = TestUtils.getTestApiGwFilename(s"testswaggerdoc2")
     try {
       var rr = apiCreate(swagger = Some(swaggerPath))
-      println("api create stdout: " + rr.stdout)
-      println("api create stderror: " + rr.stderr)
       verifyApiCreated(rr)
       rr = apiList(basepathOrApiName = Some(testbasepath))
       verifyApiFullList(rr, "", actionName, testurlop, testbasepath, testrelpath, testapiname)
@@ -804,19 +853,15 @@ abstract class ApiGwTests extends BaseApiGwTests {
 
     try {
       var rr = apiCreate(swagger = Some(swaggerPath))
-      println("api create stdout: " + rr.stdout)
-      println("api create stderror: " + rr.stderr)
       this.verifyApiCreated(rr)
 
       rr = apiList(basepathOrApiName = Some(testbasepath))
-      println("api list:\n" + rr.stdout)
       testops foreach { testurlop =>
         verifyApiOp(rr, testurlop, testapiname)
       }
       verifyApiBaseRelPath(rr, testbasepath, testrelpath)
 
       rr = apiList(basepathOrApiName = Some(testbasepath), full = Some(true))
-      println("api full list:\n" + rr.stdout)
       testops foreach { testurlop =>
         verifyApiOpVerb(rr, testurlop)
       }


 

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services