In this tutorial, we are going to learn how to develop simple Asp Net Core 3.1 Web API and API Versioning techniques such as URL-based, header-based, and Query string-based versioning.
What Is Web API Versioning? And Why Do We Need It?
Assume that we have an API available in the production box and a few clients are already consuming it. Post-production deployment, we should be very careful with any new changes. These changes should not impact the existing customer applications that are already consuming our API. It is not a good practice to advise clients to change the API calls in each of their applications where our API has been integrated. In order to address such issues, API versioning came into the picture.
API versions ensure that the integrity and availability of data for our existing client applications.
To Begin with,
Step 1
Create a simple ASP.NET Core 3.1 API Project.
Step 2
Add a model ProductResponse.cs
namespace AspNetCoreVersioning.Contracts {
public class ProductResponse {
public Guid Id {
get;
set;
}
public string Name {
get;
set;
}
}
}
Step 3
Add a Controller ProductsController.cs
namespace AspNetCoreVersioning.Controllers {
[ApiController]
[Route("api/products")]
public class ProductsController: ControllerBase {
[HttpGet("{productId}")]
public IActionResult GetProduct([FromRoute] Guid productId) {
var product = new ProductResponse {
Id = productId,
Name = "Sanitizer"
};
return Ok(product);
}
}
}
Let us test this API, According to your environment, the port number will vary.
https://localhost:12345/api/products/00000000-0000-0000-0000-000000000000
Result
{"id":"00000000-0000-0000-0000-000000000000","name":"Sanitizer"}
We have received the expected result.
Assume that we need to make a breaking change on our API, but we don’t want to break anything in our existing API which our customers are already using. How can we achieve this? Let us go and resolve a NuGet package Microsoft.AspNetCore.Mvc.Versioning.
Use the below command from the package manager console,
Install-Package Microsoft.AspNetCore.Mvc.Versioning
Once the package installation complete, let us configure the API to support versioning. This package basically has everything that we need.
Without any delay, let us go to class Startup.cs, where we are going to update the method ConfigurationServices as below
public void ConfigureServices(IServiceCollection services) {
services.AddControllers();
services.AddApiVersioning();
}
By adding these services.AddApiVersioning() method, we have some sort of versioning. However, we haven’t really told ASP.NETCore how we versioning the API. Without making any additional changes, let us run the API, we will get the below error message
{"error":{"code":"ApiVersionUnspecified","message":"An API version is required, but was not specified.","innerError":null}}
This is because we haven’t configured our API versioning to a default version. For us the first version apparently V1 or V1.0. The default way of this works in ASP.NET Core is to have the “API-version” query string parameter as below.
https://localhost:12345/api/products/00000000-0000-0000-0000-000000000000?api-version=1
Result will as below,
{"id":"00000000-0000-0000-0000-000000000000","name":"Sanitizer"}
This would work fine. However, this is not ideal because if we make this “api-version” query string is mandatory, many of our consumers’ code break. What we want to do instead is we want to enable the API versioning default to a version. How we can achieve this? Let us to the Startup.cs class again and make the below changes.
public void ConfigureServices(IServiceCollection services) {
services.AddControllers();
services.AddApiVersioning(options => {
options.AssumeDefaultVersionWhenUnspecified = true;
});
}
Let us execute the API again,
https://localhost:12345/api/products/00000000-0000-0000-0000-000000000000
Result: {"id":"00000000-0000-0000-0000-000000000000","name":"Sanitizer"}
Assume that, if we want to have a different version instead of V1.0 or V1. How can we achieve this?
First, we will make the below changes in Startup.cs class as below,
public void ConfigureServices(IServiceCollection services) {
services.AddControllers();
services.AddApiVersioning(options => {
options.AssumeDefaultVersionWhenUnspecified = true;
options.DefaultApiVersion = ApiVersion.Default;
});
}
Then make the below two changes.
Step 1
Add the below models in ProductResponse.cs Class,
namespace AspNetCoreVersioning.Contracts {
public class ProductResponseV1 {
public Guid Id {
get;
set;
}
public string Name {
get;
set;
}
}
public class ProductResponseV2 {
public Guid Id {
get;
set;
}
public string ProductName {
get;
set;
}
}
}
Step 2
Make the below changes into ProductsController.cs Class
namespace AspNetCoreVersioning.Controllers {
[ApiController]
[Route("api/products")]
public class ProductsController: ControllerBase {
[HttpGet("{productId}")]
public IActionResult GetProductV1([FromRoute] Guid productId) {
var product = new ProductResponseV1 {
Id = productId,
Name = "Sanitizer"
};
return Ok(product);
}
[HttpGet("{productId}")]
public IActionResult GetProductV2([FromRoute] Guid productId) {
var product = new ProductResponseV2 {
Id = productId,
ProductName = "Sanitizer"
};
return Ok(product);
}
}
Now Run the API. You will get the below Exception.
An unhandled exception occurred while processing the request.
AmbiguousMatchException: The request matched multiple endpoints. Matches,
AspNetCoreVersioning.Controllers.ProductsController.GetProductV2 (AspNetCoreVersioning)
AspNetCoreVersioning.Controllers.ProductsController.GetProductV1 (AspNetCoreVersioning)
Microsoft.AspNetCore.Routing.Matching.DefaultEndpointSelector.ReportAmbiguity(CandidateState[] candidateState)
In order to resolve this error message, we need to make some configuration changes at ProductsController.cs Class as below,
namespace AspNetCoreVersioning.Controllers {
[ApiController]
[Route("api/products")]
[ApiVersion("1.0")]
[ApiVersion("2.0")]
public class ProductsController: ControllerBase {
[HttpGet("{productId}")]
public IActionResult GetProductV1([FromRoute] Guid productId) {
var product = new ProductResponseV1 {
Id = productId,
Name = "Sanitizer"
};
return Ok(product);
}
[HttpGet("{productId}")]
[MapToApiVersion("2.0")]
public IActionResult GetProductV2([FromRoute] Guid productId) {
var product = new ProductResponseV2 {
Id = productId,
ProductName = "Sanitizer"
};
return Ok(product);
}
}
}
Now Run the API as below,
https://localhost:12345/api/products/00000000-0000-0000-0000-000000000000?api-version=1
Result: {"id":"00000000-0000-0000-0000-000000000000","name":"Sanitizer"}
https://localhost:12345/api/products/00000000-0000-0000-0000-000000000000?api-version=2
Result: {"id":"00000000-0000-0000-0000-000000000000","productName":"Sanitizer"}
I will be covering URL based and Header based versioning in the upcoming sessions. Thanks for reading my article. I appreciate your feedback in the comment section below.