API – Functions Part 3: Routing

In the previous part of this series, we looked at creating our first API. But how do you determine which API is being invoked? This is accomplished with routing.

If you have a Products class your entry (end point) might look like this:

[Function(nameof(Products))]
public IActionResult Run(HttpTrigger(AuthorizationLevel.Anonymous,
"get", Route="products/{category}/{id: int}")]
HttpRequest req, string category, int id)
{
  return new OkObjectResult(new {category, id});
}

Notice the routing property (“products/{category}/{id: int}” — this allows us to customize and restrict the arguments from the desired endpoint. The customer/user can now use the same endpoint for a variety of situations.

You can go further and restrict the type of the parameters, and even provide default values:

Route="products/{category:alpha}/{id: int?}")]

Here we are saying that the category must consist only of standard characters, and the id is optional.

Next up: Deploying to Azure

Note, this material is based on our book Programming APIs with C# and .NET from Packt by Jesse Liberty and Joseph Deluzen.

About Jesse Liberty

Jesse Liberty has three decades of experience writing and delivering software projects and is the author of 2 dozen books and a couple dozen online courses. His latest book, Building APIs with .NET will be released early in 2025. Liberty is a Senior SW Engineer for CNH and he was a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a Microsoft MVP.
This entry was posted in API, APIs, Essentials, Mini-Tutorial and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *