Routing & Parameters
Intermediate
20 min read
Lesson 7 of 10
The Mail Carrier Story: A mail carrier needs a specific address to deliver a letter.
MyStreet isn't enough; they need MyStreet, House #5. In APIs, the URL is the street, and the Parameters are the house numbers that pinpoint the exact data you want.
Connecting to C#
Think about C# methods. If you want a specific user, you pass an ID to the method:
public User GetUser(int id) { ... }
In a REST API, we do the exact same thing, but the ID comes from the URL!
Types of API Parameters
1. Route Parameters (The Address)
Passed directly in the URL path. Best for identifying a specific resource.
// URL: https://api.myapp.com/users/5
[HttpGet("{id}")]
public IActionResult GetUser(int id)
{
// id will be 5
return Ok($"You requested user {id}");
}
2. Query Parameters (The Filter)
Added after a question mark ?. Best for searching, sorting, or filtering.
// URL: https://api.myapp.com/products?category=electronics&maxPrice=500
[HttpGet]
public IActionResult GetProducts(string category, decimal maxPrice)
{
// category = "electronics", maxPrice = 500
return Ok($"Searching {category} under ${maxPrice}");
}
3. Body Parameters (The Package)
Used in POST and PUT requests. The data is hidden inside the HTTP request body, not the URL. Best for sending large, complex C# objects.
// The client sends a JSON object in the body
[HttpPost]
public IActionResult CreateUser([FromBody] User newUser)
{
// ASP.NET Core automatically converts the JSON to a C# User object!
return Ok($"User {newUser.Name} created!");
}