Reputation: 43
I am working on a REST API which I am testing with both Postman and Swagger. I have an endpoint with path parameters, the request url is defined like this:
{{host}}/path/:firstId/:secondId
FirstId is required, so that one will always be filled out, but SecondId is optional. So, in some examples it'll be filled out, and in others it won't. Postman, unfortunately, doesn't support optional path parameters, but I think I ought to be able to handle this with a pre-request script.
Basically I want it to check the SecondId parameter for a value, and if blank (or null) it should remove the parameter from url.
Problem is... I have no idea how to do this in Postman Javascript. Help?
Upvotes: 0
Views: 2306
Reputation: 397
This isn't most elegant solution, but should get you started on the right track. Keep in mind, this snippet assumes the following:
let params = pm.request.url.variables;
let requestURL = `${pm.environment.get('host')}/${pm.request.url.path[0]}`
params.all().forEach(param => {
if(param.key === 'firstId'){
requestURL += `/${param.value}`
}
if(param.key === 'secondId'){
if(param.value !== ""){
requestURL += `/${param.value}`
}
}
})
pm.request.url = requestURL;
Upvotes: 0