Version Interleaving – Mapping controller action to all future API versions of controller
I just have a question about what approach to take when doing minor version changes of actions in a controller
For my versioning strategy, I create a minor version for any non-breaking change made to the API.
Take the example below. I wanted to add an optional parameter to the GetUserStatus method, I created an API version 1.2 and then mapped the new method to that API version using MapToApiVersion.
[ApiVersion("1.2")]
[ApiVersion("1.1")]
[ApiVersion("1.0")]
[RoutePrefix("api/Users")]
public class TestController : BaseApiController
{
[Route("{username}/Status"), HttpGet]
public IHttpActionResult GetUserStatus(string username)
{
//get user status from Db
return Ok(Models.UserStatus.Active);
}
[Route("{username}/Status"), HttpGet]
[MapToApiVersion("1.2")]
public IHttpActionResult GetUserStatusV1_2(string username, bool includeArchivedUsers=false)
{
//get user status from Db
return Ok(Models.UserStatus.Active);
}
}
This will only include this action in api version 1.2. What approach do I take to include this action in all api versions starting from api version 1.2.
i.e. is it possible to now have api version 1.3 and 1.4 of the controller without having to add MapToApiVersion(“1.3”) and MapToApiVersion(“1.4”) to the new action?
[ApiVersion("1.4")]
[ApiVersion("1.3")]
[ApiVersion("1.2")]
[ApiVersion("1.1")]
[ApiVersion("1.0")]
[RoutePrefix("api/Users")]
public class TestController : BaseApiController
{
[Route("{username}/Status"), HttpGet]
public IHttpActionResult GetUserStatus(string username)
{
//get user status from Db
return Ok(Models.UserStatus.Active);
}
[Route("{username}/Status"), HttpGet]
[MapToApiVersion("1.2")]
public IHttpActionResult GetUserStatusV1_2(string username, bool includeArchivedUsers=false)
{
//get user status from Db
return Ok(Models.UserStatus.Active);
}
}
Thanks
Use caution with the wording non-breaking. Many service authors only consider their own worldview. While it's true that additive changes tend to be non-breaking, there is no guarantee that a service can make about its clients. Some clients may break, even with additive changes. Any visible change in the payload or breaking behavior of the service should definitely be versioned - minor or otherwise.
Since adding an optional query parameter neither changes routing nor the shape of payloads, I would say that is truly a non-breaking change. I would consider arguing that it doesn't even need to be versioned. The API version doesn't have to be congruent with the implementation version. Visible API version increments are suggesting to clients that they should update to take advantage of the latest features. In the case of adding a new query parameter, there isn't really anything to upgrade to necessarily. There's nothing wrong with minor versioning this way, but it might be an over-normalization. I'll leave it up to you to decide.
In terms of interleaving, there is no intrinsic way to achieve the result you want. An action is either implicitly matched to it's declaring parent or explicitly lists all of the corresponding API versions. Interleaving is convenient for small changes, but at some point it can become untenable to manage. At that point, it's almost certainly better to split the implementation into separate controller types.
While there are no built-in mechanisms to achieve the result you want, you can get pretty close with your own extensions. For example, you can create your own [MapToApiVersion] attribute. You can extend the built-in ApiVersionsBaseAttribute or roll your own attribute from scratch. The only requirement in all cases is that it must implement IApiVersionProvider. This can be used to provide a range.
For example:
[HttpGet]
[Route("{username}/Status")]
[MapToApiVersions(From = "1.2", To = "1.4", Step = 1)]
public IHttpActionResult GetUserStatusV1_2(string username, bool includeArchivedUsers=false)
{
return Ok(Models.UserStatus.Active);
}
In this example, Step refers to the step increment for the minor version, but you can make it as sophisticated as you need. A similar approach can be used with API version conventions, but it would likely require just as much setup and would be different from your current approach.
Ultimately, the declared API versions have to be explicit. This is primarily because the matching is discrete. I've seen fuzzing matching on ranges cause issues. The inverse, however, is not true. It's not a big issue for you to provide customizations that produce discrete ranges as suggested.
You can also apply the same approach, and technically even with the same custom attribute, at the controller level instead of [ApiVersion]. Be aware that there are some differences in usage at the action level that will not be honored, even if you specify it. [ApiVersion] and [MapToApiVersion] both implement IApiVersionProvider. They are nearly identical in implementation, but the action level intentionally hides the bits that are not relevant. The intent of having the different names and attributes was to make that as abundantly clear as possible.
I hope that guides you towards a solution that will work for you.
Great
Thank you for this detailed description and answer. I will look into this custom attribute approach.
Hi,
I've implemented this just today, where in my case I have a globally predefined "bank" of versions that each service / action can support by specifying a range. At the moment, all my services support the same versions.
To allow minimal code change to existing services when adding a new version, I implemented:
[ApiVersionRangeAll] - which adds ALL versions from the global "bank" of versions.
[ApiVersionRange(from, to)] - adds range of versions from the global "bank" of versions.
[ApiVersionRangeFrom(from)] - adds range of versions from the global "bank" of versions (implicitly to latest available version)
[ApiVersionRangeTo(to)] - adds range of versions from the global "bank" of versions (implicitly from oldest available version)
[ApiVersionRangeAll] - which adds all versions from the global "bank" of versions.
This way, decorating all my services with [ApiVersionRangeAll] and only updating the "bank" of versions does not require me to add explicit versions to all the services.
When a breaking change comes along (assuming it's small enough for interleaving), I will decorate the old action with ApiVersionRangeTo (or ApiVersionRange) and the new action with ApiVersionRangeFrom.
That seems to be working well, but what I found problematic with version range providers is deprecation. If you add a new major version and want the previous one to be reported as deprecated, you must create a separate version provider attribute with Deprecated=true. Any range of versions added with my attribute (or any attribute the implements IApiVersionProvider) is either deprecated or not.
What I originally wanted is to mark all the versions that have a lower major version than the global latest version to be deprecated, which seems not possible to do implicitly.
So,
- Do you find my above approach reasonable?
- Any way to implicitly deprecate versions as I described above?
Thanks!
-
It's less about whether I think it's reasonable and more about if it works for you. There are numerous, numerous ways to achieve composing the bits together. What was always important to me is that you can customize or otherwise change things to meet your needs as opposed to conform to my dogma. I have opinions, but that doesn't make them any more right. ;)
-
There really isn't any way to match things implicitly. "There can be only one" when it comes to implicit matching. Everything needs to be explicit to guarantee behavior. I've re-thought the problem many times and it always leads to a bad place. Remember that deprecation doesn't mean it's not supported, it just means it's expected to go away - at some point. Things need to be explicit so that when the version no longer exists, it is treated as such.
The design allows you can have sets of API versions that independently describe which versions are supported or deprecated. The sets can then be aggregated together. I can see how it might be useful to map / reduce these into your own buckets, but I'm not sure how you'd do that today. Perhaps that might be a future enhancement.
If you're struggling with making attributes work, the conventions approach might work better for you. You might have a policy per controller type (or some other key) where you rationalize supported and deprecated API versions and subsequently apply the results to the matching types. The latest release adds support for non-generic convention builders, which should make building up such policies easier.
Thanks! Correct me if I'm wrong, but when you have version interleaving it seems less preferable to control it from outside the controller. I believe that at least at first, when we have a new version of an action, it's better and safer to control the versioning in the controllers rather than the central configuration (I have quite a few controllers already...). I saw that mixing conventions and attributes is not recommended, and committing to the conversions approach doesn't seem right to me... Can you please refer me to the non-generic convention builders documentation/samples so I'll have another look?
Mixing conventions and attributes for routing is definitely not recommended because there are some scenarios where things can go sideways, but most scenarios will work. Basically, you can't switch styles for a particular service; otherwise, things appear to work. This is purely a limitation in how routing works in Web API.
Mixing API versioning between attribute and conventions, on the other hand, is not a problem. You can mix them without issue. The results of the two are unioned together (should both be specified). The libraries just treat both styles as multiple IApiVersionProvider implementations.
I tend to agree that having things close to where they apply is easier to understand and follow. The tradeoff comes when you have to make the same changes to a large number of controllers. For small-to-medium service codebases, attributes are almost certainly the way to go. For large or complex codebases, you might have policies that are applied by convention.
Conventions were originally only strongly-typed, mostly to make sure you don't make a mistake. A few people asked for non-generic support, which I can see is easier to use if you want to build complex setups; perhaps even using DI or composition. The conventions API and implementation doesn't actually vary that much. The two are so close that I didn't bother to add non-generic specific examples, but they both look like this:
AddApiVersioning(
options =>
{
// strongly-typed, generic conventions
options.Conventions.Controller<TestController>().HasApiVersion( 1, 0 );
options.Conventions.Controller<Test2Controller>()
.HasApiVersion( 2, 0 )
.HasApiVersion( 3, 0 )
.Action( c => c.GetV3() ).MapToApiVersion( 3, 0 );
// loosely-typed, non-generic conventions
options.Conventions.Controller( typeof( HelloWorldController ) ).HasApiVersion( 1, 0 );
options.Conventions.Controller( typeof( HelloWorld2Controller ) )
.HasApiVersion( 2, 0 )
.HasApiVersion( 3, 0 )
.Action( typeof( HelloWorld2Controller ).GetMethod( "GetV3" ) )
.MapToApiVersion( 3, 0 );
}
Obviously, there is still some work on your side to make this effective, but you can make a mapping of controller-to-API versions. If you don't interleave, things are relatively easy to map. Interleaving is possible (as shown), but would be very complex in trying to map. There are numerous overloads for the builder methods. In a scenario were you had a mapping of controller type and API versions, it might look like:
// TODO: build a mapping - somewhere, somehow
AddApiVersioning(
options =>
{
foreach ( var mapping in mappings )
{
options.Conventions.Controller( mapping.ControllerType )
.HasApiVersions( mapping.SupportedApiVersions )
.HasDeprecatedApiVersions( mapping.DeprecatedApiVersions );
}
}
Since you're in control of the mapping, you have more flexibility in grouping, aggregating, and so forth. It's conceptually similar to using attributes, but using a completely different method to achieve the desired result.
One of the interesting ways you might put all this together is if your controllers are organized by namespace. Your mapping determines which namespaces are supported or deprecated. The mapping discovers all controllers and bucketizes them by parsing/extracting the version number from the namespace. You can get all the defined controllers through IHttpControllerTypes in Web API or just pure Reflection in ASP.NET Core.
I'm not advocating one way or another, but these are some ways service authors can compose things however they want. ;)
Amazingly clear :) I mistakenly thought mixing attributes and conventions are bad also for versioning, thanks a lot for clarifying that! I didn't find much reference to IHttpControllerTypes though... can you please refer to its documentation? To allow the transition to ASP.NET Core in the future, might it be better to use reflection anyway?
Thanks a lot!
In Web API, it would look like this:
HttpConfiguration configuration;
var services = configuration.Services;
var assembliesResolver = services.GetAssembliesResolver();
var typeResolver = services.GetHttpControllerTypeResolver();
var controllerTypes = typeResolver.GetControllerTypes( assembliesResolver );
There isn't an complimentary service in Core that I'm aware of. Core doesn't care much about controllers; it's primarily actions. I'm sure there is some service that can get you the assemblies to consider. After that, filtering with the Reflection API should be straight forward.
Thank you! Another related question: is there a way to check attribute-based versions of a controller before applying convention-based versioning? I would like to use conventions to add versions to many controllers at once, UNLESS the controller has explicit ApiVersion attribute(s). Is that possible at all?
Thank you.
That isn't a scenario supported out-of-the-box. The default behavior unions the convention and attribute defined API versions into a distinct set as evident in ControllerApiVersionConventionBuilderBase.cs.
I don't know of anyone that has tried this - yet, but the design is meant to be extensible to support such a scenario. In a short review while digging out the links, it appears some of the things you would need to override may not be available. This is something I'm willing to fix/enhance if it's a path you want to pursue.
From your description, when your custom conventions would be applied, you would simply skip the processing if the metadata has been applied by attributes.
I think the types of complex rule processing that these scenarios want to use do not make sense to be first-class concepts in-box, but I definitely want to make sure the extension and customization points are there so you can enable or change them if you want to.
Ultimately, using custom conventions is something that you can definitely enable. There may be a few things that are not as easy change or are unchangeable when they should be. Let me know if you find any road-blockers and we can spin up a new issue to track that. In terms of wiring it up, you would just set it in the options like so:
configuration.AddApiVersioning( options =>
{
var conventions = new MyCustomConventionBuilder();
// TODO: apply your conventions
options.Conventions = conventions;
// TODO: any remaining options
}
Thanks for the quick response (again).
It looks like I would have to rewrite/duplicate the whole builder, since the existing ControllerApiVersionConventionBuilder implements the abstract methods of ControllerApiVersionConventionBuilderBase but the ApplyTo is not replaceable as it's implemented in the base class (correct me if I'm wrong).
At the moment it seems like a big overhead, and I'll probably create some mapping of the 'exceptional' controllers and perform this logic in the conventions buildup, without using attributes. It's less preferable as I wanted the developers of the services to only deal with the controllers they create, and have a central management of the conventions that apply to the 'regular' controllers (those that didn't have a breaking change, which should support all versions).
However, if you want me to help by creating an issue and help you enable this scenario, I'd be happy to.
Thanks!
@cuanp2007, it seems you are unblocked. Please come back or reopen the issue if you're not.
@nirzamir, I've opened #258 to track the enhancements required to make the convention builder fully extensible (as was originally intended). Feel free to post additional comments or needs on that issue.
Thanks