Routing In RESTful APIs Using .NET Core

 

Routing, an open debatable topic among many in the developer community, is an interesting feature in which to deep dive. Routing is a functionally based tag or Uri template used by APIs to match the desired action or methods expected to be executed. There are two types or rather two different types of Routing being used during development. Namely, ‘Convention-based Routing’ the elder son in the REST routing family followed by ‘Attribute Routing’ the most lovable son to date. As mentioned earlier it’s an open debatable topic over using which type of Routing mechanics during APIs development and designing phase as well.

In ‘Convention-based Routing’, route templates are defined by developers as per requirement, basically a set of strings of type text decorated with parameters. Once the request is received, it tries to match requested URI with this defined route templates. The only merit of using this routing type is, templates are defined at a single location in application solution structures, leveraging the template rules religiously across the controllers and actions.

Then, why is Attribute routing important? Yes, it is not only important but strongly recommended for API development by developers and architects across the communities. Though convention-based routing has its own Pros, while building a good API, there are few considerations, where this type of routing is not advisable. There are common URI patterns in REST APIs, which are tough to support by convention-based routing. Consider, a set of Response data or resources, are often clubbed with their hierarchical data or child resources. For eg. Departments have Employees, Songs have singers, Movies have actors and so on. URIs expected in such scenarios are,

/movies/1/actors

In the case of multiple controllers and huge resources this type of URI is difficult though achievable using convention-based routing, but at the cost of scaling and performance. This hits the key consideration area of designing scalable APIs. Here is where another routing type, Attribute Routing, plays a role. 

hflbigsle-1024x430

Attribute Routing

What is Attribute Routing?

Technically, Attribute routing is all about attaching a route, as an attribute, to a specific controller or action method. Decorating Controller and its method with [Route] attribute to define routes is called Attribute Routing. In simpler terms, using [Route] attribute with controllers and method is Attribute Routing.

 [Route (“api/customers/{id}/orders”)]

It started from Web API 2 and now is the most recommended and adapted Routing type in RESTful APIs design and development.

 Why use Attribute Routing?

As the name indicates, attribute routing uses attributes to define routes. Attribute routing gives you precise control over the URIs than convention-based routing in your APIs. Above described scenario of Hierarchical resources can be easily achieved by Attribute Routing, with making no compromise with the scalability of APIs.

Also, versioning APIs, overloading URI segments and multiple parameter type patterns can be achieved through attribute routing with ease.

 Working with Attribute Routing

Any route attribute on the controller makes all actions in the controller attribute routing. Defining route attribute to the action or the controller takes precedence over conventional routing. Let’s be more precise to .NET Core APIs, it comes by default with Attribute routing. Attribute routing requires detailed input to specify a route. However, it allows more control of which route template applies to each action.

Configuring

When you create a WEB API with .NET Core framework, you can notice in its Startup.cs file,

This declaration of, ‘app.UseMvc()’ at configure section, enables Attribute Routing. This are by-default configurations of .NET Core applications. Explicit configurations thus are not required for enabling Attribute routing for .NET Core Web APIs.

Below namespace is used for decorating [Route] as an attribute.

using Microsoft.AspNetCore.Mvc;

The core difference with Web API over MVC routing is that it uses the HTTP method, not the URI path, to select the action. Attribute routing also uses HTTP Action verbs to define action against methods under controller, as requested.

[HttpGet], [HttpPost], HttpPut(“{id}”)], [HttpDelete(“{id}”)] and all other documented action verbs.

In .NET Core projects, by default, Controllers are decorated with CRUD methods specifying respective HTTP action verbs.

Below is the default controller being created by .NET Core,

If you notice carefully, controller class ‘ValuesController’, is decorated by route,

[Route(“api/[controller]”)]

The feature is introduced in .NET Core framework known as Route token. The token [controller] replaces the values of the controller name from the action or class where the route is defined.

Here controller name is Values decorated by Route Controller token

Now let’s change controller name to MoviesController;

Here, URI ‘api/values’ are working perfectly  earlier, now it will throw an error (404 not found). Changing URI with ‘api/Movies’ will provide the desired response.

The same applies for [action] and [area] with their respective action methods and areas.

Now, let’s consider the below example,

For the above given code snippet,

URI,

  1. // Get /api/Movies/   will match Method 1.
  1. // Post /api/Movies/ will match Method 2.

Notice, both the URIs are the same, the only difference lies in how it’s been called, by Get or Post method. This makes Web API routing differ from MVC routing.

Patterns

Let’s look into a few other patterns with examples, as mentioned above, eased by attribute routing.

API versioning

In this example, “Get /api/movies/v1/” would be routed to a Method 1and “Get /api/movies/v2/” would get routed to Method 2.

Note, versioning is mostly taken care of with different Controllers. Here for easy understanding, we have preferred to depict it with different Methods with same signatures.

Example clearly shows, how attribute routing is the simplest way to deal with complex situations.

Overloaded URI

In this example, “id” is a parameter that could be passed as number, but “notedited” maps to a collection.

URI,

  1. // Get /api/Movies/123  will match Method 1.
  1. // Get /api/Movies/notedited will match Method 2.

Multiple Parameters Types

In this example, “id” is a parameter that could be passed as the number or as an alphabet, any free string.

URI,

  1. // Get /api/Movies/123  will match Method 1.
  1. // Get /api/Movies/abc will match Method 2.

Above example has something to be noticed, while with routing we have used,

HttpGet(“{id:int}”)]

Mentioning parameter data types to be accepted, are termed as Constraints. We will go through this in a later article.

Multiple Parameters

In this example, ‘id’and ‘authorid’ is a parameter that could be passed as number.

Matching URI:   // Get  api/books/1/author/5where 1 matches to ‘id’ and ‘5’ to authorid in the given method.

Multiple Routes

Attribute routing allows us to define multiple routes for same controller and action or method. Let’s understand it with example,

As shown in the example, Method ‘Ordermovie’ returns some value with model class ‘Movie’. The method defines two routes. One with HTTP verb Put, used mostly for updating operations in CRUD, and the other with HTTP verb Post, used for creating or adding data. Both are referring to the same method.

In this case, below URIs would be matching the routes,

URI 1 matches // PUT   api/movies/buy
URI 2 matches // Post   api/movies/checkout

Note

Route 1 & Route 2 are used for a better understanding purpose and has nothing to do with its ordering.

We can even define multiple Routes on Controller. In this case both routes from controller combines with both routes of action. See below example,

In this case, below URIs would be matching the routes,

URI 1 matches // PUT   api/movies/buy&  api/store/buy
URI 2 matches // Post   api/movies/checkout& api/store/checkout

Route Constraint

Route constraint provides control over matching parameters used in route. Syntax for defining parameters in route is “{parameter:constraint}”.

Example

Matching Routes:  api/constraint/1

Only integer value will be routed to ’Get’ method responding with valid resource. Any other non-integer value will not be entertained by method, like, api/constraint/abc will not be routed.

Here, there could be an issue. If client calls, api/constraint/0 still this would be routed to Get method, which is wrong. So to curb this issue, we can add another constraint to parameter for accepting value greater than zero. This could be achieved by adding constraint ‘min(1)’ where 1 is argument accepted by ‘min’ constraint. Arguments can be accepted in parentheses ‘( )’

We can add multiple constraints on single parameter by separating constraints by colon.

Syntax

“{parameter:constraint:constraint}”.

Example

URIs

  1. api/constraint/1 or >1 will match.
  2. api/constraint/0 will not match.
  3. api/constraint/-1 or negative number will not match.

Similarly constraints like ‘alpha’ for string, ‘bool’ for Booleanvalue, ‘datetime’ for DateTime value, ‘min’, ‘max’ , ‘range’ for values in specific range and few others can be used in route as constraint.

Attribute routing though a feature stands to be the most recommended implementation in API designing stack. Right from the scalability of APIs to making APIs readable to client, attribute routing plays an important role in APIs development. Microsoft enabling default routing as attribute routing in its .NET Core framework, closed all the possible threads of differences over using routing.