What Is API Versioning?
API versioning is the process of iterating different versions of your API.
Why Is API Versioning Required?
API versioning is required because it ensures stability and reliability. If you don’t properly version APIs, this can produce adverse effects on products and services.
As developers, we often add new features to our apps and modify current APIs, as well. Versioning enables us to safely add new functionality without breaking changes.
There are four common ways to version a REST API.
1. Versioning through URI
The most commonly used versioning is in which we can add a version to the API base URL.
Example:
http://api-demo.example.com/api/1/employee
2. Query String
Another option for versioning a REST API is to include the version number as a query parameter.
This is a straightforward way to version an API from an implementation point of view.
Example:
https://api-demo.example.com/api/employee/?api-version=2
3. Custom headers
Define a new header that contains the version number in the request as part of the request header itself.
Example:
GET https://api-demo.example.com/api/employee
Accept-Version: 3
4. Media Type
This approach allows us to version a single resource representation instead of versioning the entire API, which gives us more granular control over versioning.
Example:
GET https://api-demo.example.com/api/employee
Accept: application/json;api-version=3
Apply Versioning at Existing Web API Project
Step 1
Install Nuget Package for Versioning.
Install the “Microsoft.AspNetCore.Mvc.Versioning” package.
Step 2
To configure the API versioning properties of our project. add the below code in program.cs.
//Add Api VersioningÂ
builder.Services.AddApiVersioning(options => {
// Returns all version with depricated versions
options.ReportApiVersions = true;
options.AssumeDefaultVersionWhenUnspecified = true;
options.DefaultApiVersion = new ApiVersion(1, 0);
options.ApiVersionReader = ApiVersionReader.Combine(
//Query Strying type
new QueryStringApiVersionReader("api-version"),
//Request Heardes Type
new HeaderApiVersionReader("Accept-Version"),
//Media Type
new MediaTypeApiVersionReader("api-version"));
});
Step 3
Applying Versioning to the controllers.
Apply versioning to the controller.
Now run project.
Version 1
Version 2
Output
Output
Please do leave a comment if you find it useful. You can find the repository here.