API versioning lets an API evolve with breaking changes while existing clients keep working with the version they were built for. When you need a new version Breaking changes: removing or renaming fields or endpoints, changing data types or meaning, making optional fields required, or changing authentication and behaviour. Additive changes (new optional fields or endpoints) usually do not need a new version. Types of API versioning 1. URI path versioning: /api/v1/orders, /api/v2/orders - Most visible and common; easy to route, cache and test. Changes the resource URL. 2. Query string versioning: /api/orders?api-version=2.0 - Simple; used by many Azure APIs (often with date-based versions like 2024-10-01). 3. Header versioning: a custom header such as api-version: 2.0 or X-Api-Version: 2 - Keeps URLs clean; less visible and harder to test in a browser. 4. Media type (content negotiation) versioning: Accept: application/vnd.company.orders.v2+json - Most "RESTful" in theory; more complex for clients and tooling. Implementation in ASP.NET Core (Asp.Versioning.Mvc / Asp.Versioning.Http packages) builder.Services.AddApiVersioning(options => { options.DefaultApiVersion = new ApiVersion(1, 0); options.AssumeDefaultVersionWhenUnspecified = true; options.ReportApiVersions = true; // adds api-supported-versions / api-deprecated-versions headers options.ApiVersionReader = ApiVersionReader.Combine( new UrlSegmentApiVersionReader(), new HeaderApiVersionReader("api-version")); }).AddApiExplorer(o => { o.GroupNameFormat = "'v'VVV"; o.SubstituteApiVersionInUrl = true; }); [ApiController] [ApiVersion("1.0")] [ApiVersion("2.0")] [Route("api/v{version:apiVersion}/orders")] public class OrdersController : ControllerBase { [HttpGet("{id}"), MapToApiVersion("1.0")] public OrderV1 GetV1(int id) => ...; [HttpGet("{id}"), MapToApiVersion("2.0")] public OrderV2 GetV2(int id) => ...; } Minimal APIs use version sets: app.NewApiVersionSet().HasApiVersion(new(1, 0)).HasApiVersion(new(2, 0)).Build(). Good practices - Share business logic; keep differences in DTOs and mapping. - Publish OpenAPI documents per version. - Deprecate old versions with headers ([ApiVersion("1.0", Deprecated = true)], Sunset headers) and documentation, monitor usage, and remove versions after an announced period. - Prefer additive, backward-compatible changes to avoid creating versions unnecessarily.
Ravindra Wadile · · 0 likes