Forum Discussion

ann_joseph's avatar
ann_joseph
Copper Contributor
Aug 13, 2020

Variable substitution in rest api filter parameters

Hi All,

 

I am a beginner in powershell.I was trying to call Tableau REST APIs using powershell.To make the script generic i would need to pass the filter parameters by through a variable.In the example below,

I have a csv file filterfile,which has two columns -Fit Name,Set Name.

Fit Name    Set Name

A                   AA

B                   BB

 

I would need the filter parameter in $param to get expanded down the line in the context of invoke restmethod.Since the csv has only two rows(it can have N number of rows),the expanded values should be

 

Invoke-RestMethod -Uri "$server/api/3.5/sites/$siteID/views/$responseD/PDF?vf_Filter1=A&vf_Filter2=AA"

 

Invoke-RestMethod -Uri "$server/api/3.5/sites/$siteID/views/$responseD/PDF?vf_Filter1=B&vf_Filter2=BB"

 

sample code:

$param="vf_Filter1=$($_.{Fit Name})&vf_Filter2=$($_.{Set Name})"

Import-Csv $filterfile | ForEach-object{

Invoke-RestMethod -Uri "$server/api/3.5/sites/$siteID/views/$responseD/PDF?$Param"

}

 

Someone kindly help.

 

TIA

  • ann_joseph I think this is a good usecase for the -f format operator.

    In short, you put "anchors" in your string in the form of {0} for the first one and {1} for the second, etc. You can then "inject" actual values into those using -f.

    Here's an example of it's use in your sample:

     

    $param = 'vf_Filter1={0}&vf_Filter2={1}'
    
    Import-Csv $filterfile | ForEach-object{
        # Take $param and "inject" $_.'Fit Name' into {0} and $_.'Set Name' into {1},
        # assigning result into new variable
        $Filter = $param -f $_.'Fit Name', $_.'Set Name'
    
        $Uri = "$server/api/3.5/sites/$siteID/views/$responseD/PDF?$Filter"
        Invoke-RestMethod -Uri $Uri
    }

     

    Hope that makes sense!

    • ann_joseph's avatar
      ann_joseph
      Copper Contributor

      Joshua King  Thank you so much for the reply.

       

      I am looking to perform the inject step prior to the import-csv. So that the script can become more generic and others can just change the $param and $filter from the top portion of variable assignments rather than allowing them to edit inside the script.

      $param = 'vf_Filter1={0}&vf_Filter2={1}'
       $Filter = $param -f $_.'Fit Name', $_.'Set Name'

       

      Import-Csv $filterfile | ForEach-object{
      $Uri = "$server/api/3.5/sites/$siteID/views/$responseD/PDF?$Filter"
          Invoke-RestMethod -Uri $Uri
      }

       

      • ann_joseph's avatar
        ann_joseph
        Copper Contributor

        @Joshua King  I tried this solution.But the $Filter in the Uri is space when we put it in uri.

        Kindly help

Resources