RESTful APIs have become the standard for building and consuming web services. When designing REST APIs, one important aspect is deciding how to structure the URLs and parameters. Two common ways to pass parameters to APIs are via query string parameters and path parameters. This blog will explain the differences between these two methods, when to use each, and provide examples to illustrate their usage.
Query String Parameters
What are Query String Parameters?
Query string parameters are key-value pairs that are appended to the end of a URL, following a question mark (?). Multiple parameters are separated by an ampersand (&). They are often used to filter, sort, or paginate data.
Example of Query String Parameters
Here’s a simple example of a query string parameter used to filter results:
GET /api/products?category=electronics&sort=price
In this example.
- category is a query parameter used to filter products by the electronics category.
- sort is a query parameter used to sort products by price.
When to use Query String Parameters?
- Filtering: When you need to filter a list of items based on certain criteria.
- Sorting: When you need to sort a list of items.
- Pagination: When you need to paginate through a list of items (e.g., page=2&limit=20).
- Optional Parameters: When parameters are optional and may not always be provided.
Example in .NET Core
Here’s an example of how you might handle query string parameters in an ASP.NET Core controller:
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
[HttpGet]
public IActionResult GetProducts([FromQuery] string category, [FromQuery] string sort)
{
// Example logic to filter and sort products
var products = GetProductsFromDatabase();
if (!string.IsNullOrEmpty(category))
{
products = products.Where(p => p.Category == category).ToList();
}
if (!string.IsNullOrEmpty(sort))
{
products = sort switch
{
"price" => products.OrderBy(p => p.Price).ToList(),
_ => products
};
}
return Ok(products);
}
private List<Product> GetProductsFromDatabase()
{
// Placeholder method to get products from a database
return new List<Product>
{
new Product { Id = 1, Name = "Laptop", Category = "electronics", Price = 1000 },
new Product { Id = 2, Name = "Phone", Category = "electronics", Price = 500 },
// More products...
};
}
}
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public decimal Price { get; set; }
}
Path Parameters
What are Path Parameters?
Path parameters are part of the URL path itself and are used to identify a specific resource. They are embedded directly into the URL and are often used to retrieve, update, or delete a specific resource.

Join the conversation! Your thoughts help the community grow.