Before we focus on the goal of this blog post topic, let’s first understand the distinction between Query Parameters and URI Parameters in API Design, this is crucial for you to know. URI Parameters, also known as Path Parameters, are primarily used to identify specific resources, while Query Parameters are utilized for the sorting and filtering of these resources.
For instance, imagine a scenario where you need to identify a book by its ISBN (also known as the book ID); in this case, you’d make use of the URI parameter, something like:
GET /books/{book_id}
An example of this call should be GET /books/978-1-3999-0861-0
However, if your aim is to retrieve all the books categorized by genre, such as novels, then we should use a Query parameter, something like:
GET /books?gender={type}
An example of this call should be GET /books?gender=novels
Now that we know the key difference between Query Parameters and URI Parameters, let’s see how we can read these parameters inside Azure API Management policies.
How to read URI parameters inside Azure API Management policies
Taking the sample above, for us to read the URI parameter, we have to use the following expression:
context.Request.MatchedParameters["parameter-name"]
Using the previous sample GET /books/{book_id} the expression should be:
context.Request.MatchedParameters["book_id"]
We can also make use of the GetValueOrDefault function to retrieve the URI parameter:
context.Request.MatchedParameters.GetValueOrDefault("parameter-name","optional-default-value")
And, of course, we can apply this expression to several operations like:
- Check URI parameter existence:
- context.Request.MatchedParameters.ContainsKey(“book_id”) == true
- Check if the URI parameter has the expected value:
- context.Request.MatchedParameters.GetValueOrDefault(“book_id”, “”).Equals(“978-1-3999-0861-0”, StringComparison.OrdinalIgnoreCase) == true
How to read Query parameters inside Azure API Management policies
Once again, taking the sample above, for us to read the URI parameter, we have to use the following expression:
ccontext.Request.Url.Query["parameter-name"]
We can also make use of the GetValueOrDefault function to retrieve the URI parameter:
context.Request.Url.Query.GetValueOrDefault("parameter-name", "optional-default-value")
Using the previous sample GET /books?gender={type} the expression should be:
context.Request.Url.Query.GetValueOrDefault("type")]
And, of course, we can apply this expression to several operations like:
- Check Query parameter existence:
- context.Request.Url.Query.ContainsKey(“type”) == true
- Check if the Query parameter has the expected value:
- context.Request.Url.Query.GetValueOrDefault(“type”, “”).Equals(“Novels”, StringComparison.OrdinalIgnoreCase) == true
Hope you find this helpful! So, if you liked the content or found it helpful and want to help me write more content, you can buy (or help buy) my son a Star Wars Lego!