Thomas Due
Thomas Due

Reputation: 43

Handling optional path parameters in Postman

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

Answers (1)

brandon-estrella-dev
brandon-estrella-dev

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:

  1. {{host}} is defined as an environment variable.
  2. {{host}} does not contain a trailing slash.
  3. firstId is expected to exist.
  4. The path will not change.
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

Related Questions