web-api
  1. web-api-versioning-and-query-string-parameter

Versioning and Query String Parameter - (Web API Versioning)

Web API versioning provides a way to maintain compatibility between client applications and APIs. When an API changes, versioning allows clients to continue to use an older version of the API while developers update their client applications to use the new version. This page explains how to version a Web API using query string parameters.

Syntax

To version a Web API using query string parameters, you will need to include the version number in the query string of the API call. Here is an example of a versioned API call:

https://myapi.com/api/products?api-version=1.0

Example

Here is an example of how to version a Web API using query string parameters:

using Microsoft.AspNetCore.Mvc;

namespace MyNamespace.Controllers
{
  [ApiController]
  [Route("api/products")]
  public class ProductsController : ControllerBase
  {
    [HttpGet]
    public ActionResult<string> GetV1()
    {
      return "This is version 1 of the products API";
    }

    [HttpGet]
    [Route("v2")]
    public ActionResult<string> GetV2()
    {
      return "This is version 2 of the products API";
    }
  }
}

Output

When you call the endpoint with the api-version=1.0 query string parameter, you should see the following output:

This is version 1 of the products API

When you call the endpoint with the api-version=2.0 query string parameter, you should see the following output:

This is version 2 of the products API

Explanation

In the example code, we define a ProductsController with two actions that return a string. The first action, GetV1(), is not versioned and returns a message indicating that it is version 1 of the products API. The second action, GetV2(), is version 2 of the products API and is accessed via the /v2 route. By including the api-version query string parameter in the API call, clients can specify which version of the API they want to use.

Use

Versioning Web APIs using query string parameters is a common method of maintaining compatibility between client applications and APIs. By including the version number in the query string of the API

Published on: