Add API Versioning using URL Versioning in .NET

API Versioning using URL Versioning in NET

Today in this article, we shall learn how to enable or add API Versioning using URL Versioning in .NET. In this type of versioning technique, you add a version number to the URI for each resource.

Existing URIs continue to operate as per contract, returning resources that conform to the original schema.

Using the version specified in the API route the REST API allows accepting the request in any format like JSON or XML. The version specified in each URL URL gives the resource of different types as required by the client.

Currently, the parameters used in media types for content negotiation can be content in detail to derive the API versioning on the server-side.

As we understood in our last article Change in API is inevitable and API versioning comes to the rescue to protect your API from any breaking changes or changes in resources for any new requirements more importantly without breaking any existing clients.

However, as I understood, this versioning works with limited features only in the ASP.NET Core.

Today in this article, we will cover below aspects,

For more detail on other API versioning techniques, please please visit the below article,

API Versioning using URL Versioning

Getting started

Let’s create ASP.NET Core API using ASP.NET Core .NET 5 or .NET 6,

URL API Versioning NET 5

Please install below NuGet package,

PM> Install-Package Microsoft.AspNetCore.Mvc.Versioning -Version 4.1.1

Or

Install from NuGet Package Manager,

api versioning best practices

Please update the ConfigureServices method to add the MediaTypeApiVersionReader service to the service collection as below,

Step1

In this type of versioning technique, you add a version number to the URI for each resource.

Existing URIs continue to operate as per contract, returning resources that conform to the original schema.

services.AddApiVersioning(option =>
            {
                option.DefaultApiVersion = new ApiVersion(1, 0);
                option.AssumeDefaultVersionWhenUnspecified = true;
                option.ApiVersionReader = new UrlSegmentApiVersionReader();

            });

Step2

Register API URL versioning by explicit opt-in as below,

URL Versioning best practices, api versioning .net core swagger, api versioning .net core 6, api versioning net 6, asp.net core api versioning microsoft, asp.net core web api versioning best practices, net 6 api versioning swagger, web api versioning best practices c#, asp.net web api versioning best practices,

Assign annotation [ApiVersion] at the Controller/Method level and then use any of the versioning techniques as enabled in the ConfigureServices method.

Here is the c Please see below the complete code,

  

    [ApiController]
    [Route("api/v{version:apiVersion}/[controller]")]
    [ApiVersion("1.0")]
    [ApiVersion("2.0")]
    [ApiVersion("3.0")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
       {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }

        [HttpGet]
        [MapToApiVersion("1.0")]
        public IEnumerable<WeatherForecast> GetWatherUSA()
        {
            var rng = new Random();
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            })
            .ToArray();
        }

        [HttpGet]
        [MapToApiVersion("2.0")]
        public IEnumerable<WeatherForecastNew> GetWeatherUK()
        {
            var rng = new Random();
            return Enumerable.Range(1, 5).Select(index => new WeatherForecastNew
            {
                DateOfForcast = DateTime.Now.AddDays(index),
                Temperature = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            })
            .ToArray();
        }

        [HttpGet]
        [MapToApiVersion("3.0")]
        public IEnumerable<WeatherForecastIndia> GetWeatherIndia()
        {
            var rng = new Random();
            return Enumerable.Range(1, 5).Select(index => new WeatherForecastIndia
            {
                ForcastDay = DateTime.Now.AddDays(index),
                Temperature = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            })
            .ToArray();
        }
    }

Release API as 1.0

API query versioning

Release API as 2.0

API header versioning

Above we are able to add a version number to the URL itself and able to fetch the required resources.

Let’s see the v1 version execution,

So here V1.0 produces the below JSON result,

 {
        "dateOfForcast": "2020-05-08T18:10:03.1268402-04:00",
        "temperature": 22,
        "temperatureFerehnite": 71,
        "summary": "Bracing"
    }

Let’s try executing V2.0 version,

   {
        "date": "2020-05-08T18:11:00.1929376-04:00",
        "temperatureC": 32,
        "temperatureF": 89,
        "summary": "Bracing"
    }

Add QueryString API Versioning

For more details visit- Add QueryString API Versioning

Header/Media API versioning in .NET

For more details visit: Header/Media API versioning in .NET

References :

Do you have any comments or ideas or any better suggestions to share?

Please sound off your comments below.

Happy Coding !!



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



2 thoughts on “API Versioning using URL Versioning in .NET

Leave a Reply

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