Back to API Versioning & Content Negotiation
Q2Question 2 of 2

How do you version a REST API and maintain backward compatibility

Answer: API versioning is the practice of maintaining multiple versions of an API simultaneously so that new features and changes can be introduced without breaking existing clients.

Key Concepts
  • API versioning lets you evolve your REST API without breaking existing clients that depend on the current contract.
  • URI versioning (/v1/accounts) is the most visible and widely adopted approach in banking APIs.
  • Header versioning (X-API-Version: 2) keeps URIs clean but is harder to test with a browser.
  • Media-type versioning (Accept: application/vnd.bank.v2+json) follows HTTP semantics most closely.
  • The expand-and-contract pattern adds new fields first, migrates clients, then removes old fields in a later version.
  • Never remove or rename a field in an existing version because that is a breaking change for all current consumers.
  • Deprecation headers (Sunset, Deprecation) warn clients before an old version is removed.

Definition

API versioning is the practice of maintaining multiple versions of an API simultaneously so that new features and changes can be introduced without breaking existing clients.
  • API versioning allows you to evolve the API contract (add fields, change structure, rename endpoints) while keeping older clients working on the previous version.
  • Breaking change is any modification that causes an existing client to fail: removing a field, renaming a field, changing a field's type, or altering response structure.
  • Non-breaking change is a modification that existing clients can ignore: adding a new optional field, adding a new endpoint, or adding a new query parameter.
  • Backward compatibility means new versions of the API can serve old clients without errors.
  • Expand-and-contract is a migration pattern where you add the new field alongside the old one, migrate clients, and then remove the old field in a future version.

Think of National Bank of India updating their account statement format. The old format shows balance as a single number. The new format shows balance as an object with currency and amount. If the bank switches overnight, every ATM, mobile app, and third-party integration that reads the old format breaks. Instead, the bank releases the new format as "Version 2" while keeping Version 1 running. ATMs upgrade at their own pace. Once all ATMs are on Version 2, the bank retires Version 1.

Understanding the Concepts

What is API versioning?

API versioning is the practice of running multiple versions of the same API simultaneously. When you need to make a breaking change to your API, you release a new version. Existing clients continue using the old version until they are ready to migrate. New clients use the latest version.

Without versioning, any breaking change (removing a field, changing a type, restructuring the response) breaks every client at once. For a banking API serving mobile apps, ATMs, and third-party payment gateways, this is unacceptable.

JAVA
package com.bank.dto.v1;

import java.math.BigDecimal;

// Version 1: balance is a simple BigDecimal
public record AccountResponseV1(
    String accountId,
    String holderName,
    BigDecimal balance,
    String type
) {}
JAVA
package com.bank.dto.v2;

import java.math.BigDecimal;

// Version 2: balance is an object with currency
public record AccountResponseV2(
    String accountId,
    String holderName,
    BalanceInfo balance,
    String type,
    String email  // new field in V2
) {
    public record BalanceInfo(
        BigDecimal amount,
        String currency
    ) {}
}
TEXT
// V1 response:
{"accountId":"SAV2001","holderName":"Rajesh Kumar","balance":75000.00,"type":"SAVINGS"}

// V2 response (breaking change: balance is now an object):
{"accountId":"SAV2001","holderName":"Rajesh Kumar","balance":{"amount":75000.00,"currency":"INR"},"type":"SAVINGS","email":"rajesh@nationalbank.in"}

Why do you need API versioning?

APIs evolve. Business requirements change, new regulations appear, and the data model grows. Some changes are backward-compatible (additive), but others are not.

  • Non-breaking changes (no versioning needed):
  • Adding a new optional field to the response.
  • Adding a new endpoint.
  • Adding a new optional query parameter.
  • Breaking changes (versioning required):
  • Removing a field from the response.
  • Renaming a field.
  • Changing a field's data type (BigDecimal to String, or flat value to nested object).
  • Changing the response structure.
  • Removing an endpoint.
  • Changing authentication requirements.
JAVA
package com.bank.service;

import com.bank.dto.v1.AccountResponseV1;
import com.bank.dto.v2.AccountResponseV2;
import com.bank.model.Account;
import com.bank.repository.AccountRepository;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;

@Service
public class AccountService {

    private final AccountRepository repository;

    public AccountService(AccountRepository repository) {
        this.repository = repository;
    }

    public AccountResponseV1 findByIdV1(String accountId) {
        Account account = repository.findById(accountId).orElseThrow();
        return new AccountResponseV1(
            account.getAccountId(),
            account.getHolderName(),
            account.getBalance(),
            account.getType());
    }

    public AccountResponseV2 findByIdV2(String accountId) {
        Account account = repository.findById(accountId).orElseThrow();
        return new AccountResponseV2(
            account.getAccountId(),
            account.getHolderName(),
            new AccountResponseV2.BalanceInfo(
                account.getBalance(), "INR"),
            account.getType(),
            account.getEmail());
    }
}
TEXT
// V1 client expects: "balance": 75000.00
// V2 client expects: "balance": {"amount": 75000.00, "currency": "INR"}
// Both work simultaneously because each version has its own endpoint

How does URI versioning work?

URI versioning puts the version number directly in the URL path. This is the most common and most visible approach.

JAVA
package com.bank.controller.v1;

import com.bank.dto.v1.AccountResponseV1;
import com.bank.service.AccountService;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("/api/v1/accounts")
public class AccountControllerV1 {

    private final AccountService accountService;

    public AccountControllerV1(AccountService accountService) {
        this.accountService = accountService;
    }

    @GetMapping("/{accountId}")
    public AccountResponseV1 getAccount(
            @PathVariable String accountId) {
        return accountService.findByIdV1(accountId);
    }
}
JAVA
package com.bank.controller.v2;

import com.bank.dto.v2.AccountResponseV2;
import com.bank.service.AccountService;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/v2/accounts")
public class AccountControllerV2 {

    private final AccountService accountService;

    public AccountControllerV2(AccountService accountService) {
        this.accountService = accountService;
    }

    @GetMapping("/{accountId}")
    public AccountResponseV2 getAccount(
            @PathVariable String accountId) {
        return accountService.findByIdV2(accountId);
    }
}
TEXT
GET /api/v1/accounts/SAV2001
{"accountId":"SAV2001","holderName":"Rajesh Kumar","balance":75000.00,"type":"SAVINGS"}

GET /api/v2/accounts/SAV2001
{"accountId":"SAV2001","holderName":"Rajesh Kumar","balance":{"amount":75000.00,"currency":"INR"},"type":"SAVINGS","email":"rajesh@nationalbank.in"}

Advantages: easy to understand, easy to test in a browser, easy to route at the API gateway. Disadvantage: the URI changes between versions, so bookmarks and hardcoded links break.

How does header versioning work?

Header versioning uses a custom request header to specify the version. The URI stays the same across versions.

JAVA
package com.bank.controller;

import com.bank.dto.v1.AccountResponseV1;
import com.bank.dto.v2.AccountResponseV2;
import com.bank.service.AccountService;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/accounts")
public class AccountVersionedController {

    private final AccountService accountService;

    public AccountVersionedController(AccountService accountService) {
        this.accountService = accountService;
    }

    @GetMapping(value = "/{accountId}",
        headers = "X-API-Version=1")
    public AccountResponseV1 getAccountV1(
            @PathVariable String accountId) {
        return accountService.findByIdV1(accountId);
    }

    @GetMapping(value = "/{accountId}",
        headers = "X-API-Version=2")
    public AccountResponseV2 getAccountV2(
            @PathVariable String accountId) {
        return accountService.findByIdV2(accountId);
    }
}
TEXT
GET /api/accounts/SAV2001
X-API-Version: 1
{"accountId":"SAV2001","holderName":"Rajesh Kumar","balance":75000.00,"type":"SAVINGS"}

GET /api/accounts/SAV2001
X-API-Version: 2
{"accountId":"SAV2001","holderName":"Rajesh Kumar","balance":{"amount":75000.00,"currency":"INR"},"type":"SAVINGS","email":"rajesh@nationalbank.in"}

Advantages: URIs stay clean and stable. Disadvantage: harder to test in a browser, requires clients to set the custom header.

How does media-type versioning work?

Media-type versioning uses the Accept header with a custom media type. This is the most HTTP-purist approach.

JAVA
package com.bank.controller;

import com.bank.dto.v1.AccountResponseV1;
import com.bank.dto.v2.AccountResponseV2;
import com.bank.service.AccountService;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/accounts")
public class AccountMediaTypeController {

    private final AccountService accountService;

    public AccountMediaTypeController(AccountService accountService) {
        this.accountService = accountService;
    }

    @GetMapping(value = "/{accountId}",
        produces = "application/vnd.nationalbank.v1+json")
    public AccountResponseV1 getAccountV1(
            @PathVariable String accountId) {
        return accountService.findByIdV1(accountId);
    }

    @GetMapping(value = "/{accountId}",
        produces = "application/vnd.nationalbank.v2+json")
    public AccountResponseV2 getAccountV2(
            @PathVariable String accountId) {
        return accountService.findByIdV2(accountId);
    }
}
TEXT
GET /api/accounts/SAV2001
Accept: application/vnd.nationalbank.v1+json
{"accountId":"SAV2001","holderName":"Rajesh Kumar","balance":75000.00,"type":"SAVINGS"}

GET /api/accounts/SAV2001
Accept: application/vnd.nationalbank.v2+json
{"accountId":"SAV2001","holderName":"Rajesh Kumar","balance":{"amount":75000.00,"currency":"INR"},"type":"SAVINGS","email":"rajesh@nationalbank.in"}

Advantages: most aligned with HTTP content negotiation. Disadvantage: hardest to test, least familiar to most developers.

How do you compare the three approaches?

CriterionURI VersioningHeader VersioningMedia-Type Versioning
VisibilityVersion in the URL, easy to seeHidden in headersHidden in Accept header
Browser testableYesNo (need Postman/curl)No (need Postman/curl)
CachingCache-friendly (different URIs)Requires Vary headerRequires Vary header
URI stabilityURI changes per versionURI stays the sameURI stays the same
API gateway routingEasy path-based routingRequires header inspectionRequires content-type inspection
AdoptionMost common (GitHub, Stripe)Some APIs (Azure)Less common (GitHub for some)
Best for bankingPrimary choiceSecondary optionNiche use

For most banking APIs at National Bank of India, URI versioning is the recommended choice. It is the easiest to understand, route, cache, and test.

TEXT
// Recommendation for National Bank of India:
// 1. Use URI versioning: /api/v1/accounts, /api/v2/accounts
// 2. Run both versions simultaneously during migration
// 3. Set a sunset date for the old version
// 4. Communicate the timeline to all API consumers

What is the expand-and-contract pattern?

Expand-and-contract is a migration strategy for evolving an API without a version bump. You expand the response by adding new fields alongside old ones, migrate clients, and then contract by removing the old fields.

Phase 1: Expand (add the new field, keep the old one)

JAVA
package com.bank.dto;

import java.math.BigDecimal;

// Phase 1: Both "balance" (old) and "balanceInfo" (new) present
public record AccountResponseExpanded(
    String accountId,
    String holderName,
    BigDecimal balance,             // old: keep for backward compat
    BalanceInfo balanceInfo,        // new: clients migrate to this
    String type
) {
    public record BalanceInfo(
        BigDecimal amount,
        String currency
    ) {}
}
TEXT
GET /api/v1/accounts/SAV2001
{
  "accountId": "SAV2001",
  "holderName": "Rajesh Kumar",
  "balance": 75000.00,
  "balanceInfo": {"amount": 75000.00, "currency": "INR"},
  "type": "SAVINGS"
}
// Old clients read "balance". New clients read "balanceInfo".
// No one breaks.

Phase 2: Migrate (all clients switch to the new field)

TEXT
// Monitor API logs to track which clients still read "balance".
// Once all clients use "balanceInfo", proceed to Phase 3.

Phase 3: Contract (remove the old field)

JAVA
package com.bank.dto;

import java.math.BigDecimal;

// Phase 3: Only the new field remains
public record AccountResponseContracted(
    String accountId,
    String holderName,
    BalanceInfo balanceInfo,
    String type
) {
    public record BalanceInfo(
        BigDecimal amount,
        String currency
    ) {}
}
TEXT
GET /api/v1/accounts/SAV2001
{
  "accountId": "SAV2001",
  "holderName": "Rajesh Kumar",
  "balanceInfo": {"amount": 75000.00, "currency": "INR"},
  "type": "SAVINGS"
}

What are common mistakes in API versioning?

Mistake 1: Versioning too eagerly

WRONG: Creating a new version for every change, including non-breaking ones.

TEXT
// WRONG: v1, v2, v3, v4, v5 in six months
/api/v1/accounts  (initial)
/api/v2/accounts  (added email field)
/api/v3/accounts  (added phone field)
/api/v4/accounts  (added createdAt field)
/api/v5/accounts  (changed balance to object)

// Only v5 is a breaking change. v2-v4 were additive and
// did not need a new version.

CORRECT: Only version for breaking changes. Add new optional fields without bumping the version.

TEXT
// CORRECT:
/api/v1/accounts  (initial + email + phone + createdAt over time)
/api/v2/accounts  (balance changed from number to object)

Mistake 2: Not communicating deprecation

WRONG: Removing the old version without warning.

TEXT
// WRONG: v1 just stops working one day
// Clients get 404 Not Found with no explanation

CORRECT: Use deprecation headers and a sunset date.

JAVA
package com.bank.controller.v1;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/v1/accounts")
public class AccountControllerV1 {

    @GetMapping("/{accountId}")
    public ResponseEntity<AccountResponseV1> getAccount(
            @PathVariable String accountId) {
        AccountResponseV1 response = accountService.findByIdV1(accountId);
        return ResponseEntity.ok()
            .header("Deprecation", "true")
            .header("Sunset", "Sat, 01 Mar 2026 00:00:00 GMT")
            .header("Link",
                "</api/v2/accounts/" + accountId + ">; rel=\"successor-version\"")
            .body(response);
    }
}
TEXT
GET /api/v1/accounts/SAV2001
HTTP 200 OK
Deprecation: true
Sunset: Sat, 01 Mar 2026 00:00:00 GMT
Link: </api/v2/accounts/SAV2001>; rel="successor-version"
{"accountId":"SAV2001","holderName":"Rajesh Kumar","balance":75000.00,"type":"SAVINGS"}

What should a senior or principal engineer know?

- Semantic versioning for APIs. Use MAJOR.MINOR for API versions. Major version increments for breaking changes. Minor version increments are communicated in documentation but do not change the URI.

- API gateway version routing. In microservices, the API gateway routes /api/v1/* to the V1 deployment and /api/v2/* to the V2 deployment. This allows you to run different versions as separate services or separate deployments of the same service.

- Consumer-driven contract testing. Use Pact or Spring Cloud Contract to verify that your API changes do not break consumers. Each consumer records what fields and endpoints it uses. The provider runs these contracts in CI to catch breaking changes before deployment.

- GraphQL as an alternative to versioning. GraphQL APIs rarely need versioning because clients specify exactly which fields they want. Adding a new field does not affect existing queries. However, GraphQL introduces complexity (schema design, N+1 queries, batching) that may not be worth it for a straightforward banking CRUD API.

- Feature flags over versioning. For internal APIs within a microservices architecture, feature flags can be more practical than full versioning. A header like X-Features: balance-v2 enables the new behavior for opted-in clients.

- Version lifecycle management. Define a clear policy: support N and N-1 versions. When N+1 is released, N-1 enters sunset with a deprecation header and a removal date. Monitor usage of old versions through API gateway metrics.

JAVA
package com.bank.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class VersionDeprecationConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new DeprecationInterceptor())
            .addPathPatterns("/api/v1/**");
    }
}
JAVA
package com.bank.config;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import java.util.logging.Logger;

public class DeprecationInterceptor implements HandlerInterceptor {

    private static final Logger log =
        Logger.getLogger(DeprecationInterceptor.class.getName());

    @Override
    public boolean preHandle(
            HttpServletRequest request,
            HttpServletResponse response,
            Object handler) {

        response.setHeader("Deprecation", "true");
        response.setHeader("Sunset",
            "Sat, 01 Mar 2026 00:00:00 GMT");

        log.warning("Deprecated V1 API called: "
            + request.getRequestURI()
            + " by client: "
            + request.getHeader("User-Agent"));

        return true; // allow the request to proceed
    }
}
TEXT
// Every V1 request now gets deprecation headers automatically
// and logs which client is still using V1
WARNING: Deprecated V1 API called: /api/v1/accounts/SAV2001 by client: NBI-MobileApp/3.2

What are common interview follow-up questions?

  • What is the difference between a breaking and non-breaking change?
  • How do you migrate 500 API consumers from V1 to V2 without downtime?
  • When would you use expand-and-contract instead of a new version?
  • How does content negotiation work with the Accept header?
  • What is the Sunset HTTP header and when do you use it?
  • How do you test backward compatibility in CI/CD?
  • What is consumer-driven contract testing?
  • When would you choose GraphQL over REST versioning?
  • How do you handle versioning in a microservices architecture?
  • What is the recommended number of concurrent API versions to support?

Visual Overview

TEXT
  API Versioning Approaches
  =========================

  1. URI Versioning
     GET /api/v1/accounts/SAV2001  -> V1 response
     GET /api/v2/accounts/SAV2001  -> V2 response

  2. Header Versioning
     GET /api/accounts/SAV2001
     X-API-Version: 1              -> V1 response
     X-API-Version: 2              -> V2 response

  3. Media-Type Versioning
     GET /api/accounts/SAV2001
     Accept: application/vnd.nationalbank.v1+json  -> V1
     Accept: application/vnd.nationalbank.v2+json  -> V2
TEXT
  Expand-and-Contract Pattern
  ===========================

  Phase 1: EXPAND
  +--------------------------------------------+
  | {"balance": 75000, "balanceInfo": {...}}   |
  | Old field + New field = both present        |
  +--------------------------------------------+
              |
              v
  Phase 2: MIGRATE
  +--------------------------------------------+
  | All clients switch to "balanceInfo"         |
  | Monitor logs: who still reads "balance"?    |
  +--------------------------------------------+
              |
              v
  Phase 3: CONTRACT
  +--------------------------------------------+
  | {"balanceInfo": {...}}                     |
  | Old field removed. Only new field remains.  |
  +--------------------------------------------+

Key Takeaway

API versioning is how you evolve a banking API without breaking the mobile apps, ATMs, and payment gateways that depend on it. When you need to change the response structure, rename a field, or alter a data type, you release a new version. Existing clients keep using the old version until they migrate.

The three main approaches are URI versioning, header versioning, and media-type versioning. URI versioning is the most widely used because it is visible, cacheable, and easy to route at the API gateway. Header and media-type versioning keep URIs clean but require tools like Postman or curl to test.

The expand-and-contract pattern avoids versioning altogether for gradual changes. You add the new field alongside the old one, wait for clients to migrate, and then remove the old field. This works well for simple field additions but is not suitable when the response structure changes dramatically.

In a production banking system, version lifecycle management matters. Support N and N-1 versions. Use deprecation headers and sunset dates to communicate timelines. Monitor which clients still use old versions through API gateway logs. Consumer-driven contract tests in CI catch breaking changes before deployment.

Remember one sentence: version your API for breaking changes, use expand-and-contract for gradual evolution, and always warn consumers before retiring an old version.

---

Share
Use ← → arrow keys to navigate