Typically when designing your API, query string parameters should be reserved for optional arguments.
So for example if ID is a required parameter, it is better to use this as the URI:
https://example.api.com/product/1234
instead of this:
https://example.api.com/product?id=1234
where 1234 is the ID of the requested product.
Of course there are always exceptions and I had a situation where I wanted to use a required query parameter.
ASP.NET Core can help you there by using the [Required] or [BindRequired] attributes on your action method parameters:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[ApiController] | |
[Route("[controller]")] | |
public class ProductController : ControllerBase | |
{ | |
[HttpGet] | |
public IActionResult Get([Required] int id) => Ok(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[ApiController] | |
[Route("[controller]")] | |
public class ProductController : ControllerBase | |
{ | |
[HttpGet] | |
public IActionResult Get([BindRequired] int id) => Ok(); | |
} |
Both controllers will return a validation error when invoked without the id parameter:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1", | |
"title": "One or more validation errors occurred.", | |
"status": 400, | |
"traceId": "|7fb5e16a-4c8f23bbfc974667.", | |
"errors":{ | |
"Id":[ | |
"A value for the 'Id' parameter or property was not provided." | |
] | |
} | |
} |