How to parameterize tokens in URL for web service requests in VisualStudio webtest

While back I had blogged about automating testing of your REST API using VisualStudio webtest and one of the questions I got was how do you parameterize tokens in URL for REST API endpoints. If you have not seen that post see this link. Let’s take a look at our northwind API as an example.

If you want to retrieve a single customer entity and the REST API endpoint looks something like this{customerID}

By default if you add a web service request to your webtest you will need to hardcode the “customerID” portion in the above API endpoint. This may not be necessarily bad if those IDs never change additionally if you have multiple web service requests added in your webtests for different scenarios, if you hard code the ID in URL and when the IDs change you will have to make sure you go and update all the URLs for each web service requests in your webtest which can quickly become a nightmare. So lets see how we can solve that problem.

Approach 1:

Add a context parameter to your webtest called “customerIDParam” and set the value to a customer ID that you will use as test data for the webtest. Follow steps to add context parameter.

Assuming the webtest is open in VisualStudio, right click on context parameters node and select “add context parameter”


enter name you want to use for the parameter and for value enter the customer ID you will use as test data.

Once the context parameter is setup, you can now use this in the URL for the web service request as shown below. In the highlighted request you can see the API host portion and customer ID portion using context parameters.


Approach 2:

This approach we are going to use some custom code to get the parameters for the webtest. First thing we’ll need to do is add a data source to the webtest project, datasource will contain the the test data that we want to use, in this case api host and customer ID values. Next thing we’ll need to do is convert the webtest into a coded webtest. One thing to keep in mind here is that the VisualStudio designer doesn’t allow binding URLs to datasource, it would have been nice if we could do that as that would eliminate having to write custom code.

To convert the webtest into a coded webtest, assuming you’ve opened the webtest inside of VisualStudio, click on “Generate Code” toolbar option as shown in screen capture below


You could also just simply add a class and inherit from “WebTest” class defined in “Microsoft.VisualStudio.TestTools.WebTesting” namespace. I’m not sure why there is no option to added coded web test within VisualStudio that would automatically do this.

Assuming you have the coded webtest class added to the project we can get apihost and customer id values from the datasource by adding below code to the coded webtest and use it when we construct the “WebTestRequest”


Hope that helps