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.
📌Explore more at: https://dotnet-fullstack-dev.blogspot.com/
🌟 Sharing would be appreciated! 🚀
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.
Example of Path Parameters
Here’s an example of a path parameter used to retrieve a specific product by its ID:
GET /api/products/123
In this example.
123 is a path parameter used to specify the ID of the product to retrieve.
When to Use Path Parameters?
- Resource Identification: When the parameter is needed to identify a specific resource.
- Mandatory Parameters: When the parameter is required to complete the request.
Example in .NET Core
Here’s an example of how you might handle path parameters in an ASP.NET Core controller.
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
[HttpGet("{id}")]
public IActionResult GetProductById(int id)
{
// Example logic to retrieve a product by ID
var product = GetProductFromDatabase(id);
if (product == null)
{
return NotFound();
}
return Ok(product);
}
private Product GetProductFromDatabase(int id)
{
// Placeholder method to get a product from a database
var products = 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...
};
return products.FirstOrDefault(p => p.Id == id);
}
}
Combining Query String and Path Parameters
It’s often useful to combine both query string and path parameters in a single API. For example, you might use a path parameter to identify a specific resource and query string parameters to filter or sort related data.
Example
Here’s an example of an API that retrieves orders for a specific customer (identified by a path parameter) and supports filtering by order status (using a query string parameter).
GET /api/customers/123/orders?status=shipped
Example in .NET Core
Here’s how you might implement this in an ASP.NET Core controller.
[ApiController]
[Route("api/[controller]")]
public class CustomersController : ControllerBase
{
[HttpGet("{customerId}/orders")]
public IActionResult GetCustomerOrders(int customerId, [FromQuery] string status)
{
// Example logic to retrieve orders for a specific customer and filter by status
var orders = GetOrdersFromDatabase(customerId);
if (!string.IsNullOrEmpty(status))
{
orders = orders.Where(o => o.Status == status).ToList();
}
return Ok(orders);
}
private List<Order> GetOrdersFromDatabase(int customerId)
{
// Placeholder method to get orders from a database
return new List<Order>
{
new Order { Id = 1, CustomerId = 123, Status = "shipped", Total = 50.00m },
new Order { Id = 2, CustomerId = 123, Status = "processing", Total = 100.00m },
// More orders...
};
}
}
public class Order
{
public int Id { get; set; }
public int CustomerId { get; set; }
public string Status { get; set; }
public decimal Total { get; set; }
}
Conclusion
Understanding when to use query string parameters and path parameters is crucial for designing intuitive and effective REST APIs. Query string parameters are ideal for filtering, sorting, and pagination, while path parameters are used for resource identification. Combining both can provide a flexible and powerful way to interact with your APIs.
By following the guidelines and examples provided in this blog, you can design well-structured REST APIs that are easy to use and maintain.
Top comments (0)