Java Academy

Master Java Development

Menu

Core Java

Servlets

JDBC

Microservices

Build Tools

APIs

APIs · Lesson 7

API Versioning

Why APIs Need Versions

An API version protects existing clients while a contract evolves. Versioning is useful when a response shape, validation rule, or behavior must change incompatibly. A version should represent a supported contract, not every small implementation change.

Versioning a Representation

A versioned response can make the contract explicit while the service internally uses a shared domain model. The public representation should include only fields the client is meant to rely on.

public record CourseResponseV2(long id, String title, int completedLessons, int totalLessons) {
    public double completionRatio() {
        return totalLessons == 0 ? 0.0 : (double) completedLessons / totalLessons;
    }

    public static void main(String[] arguments) {
        CourseResponseV2 course = new CourseResponseV2(12, "Servlets", 6, 12);
        System.out.println(course.completionRatio());
    }
}

Versioning Strategies

StrategyExampleStrength
URL path/api/v2/coursesEasy to see and route
HeaderAccept: application/vnd.academy.v2+jsonKeeps URLs stable
Query parameter/courses?version=2Simple to try
No versionCompatible evolution onlyLowest overhead

Common Mistake and Practices

Common Mistake: Creating a new version for every additive field. Adding optional fields is often backward compatible and does not need a new contract.

  • Version only breaking changes.
  • Publish migration guidance.
  • Track client usage before retiring versions.
  • Keep old versions isolated and tested.
  • Use semantic compatibility rules consistently.

Real-World Use Case

A mobile application continues using API v1 while a web client adopts v2 with richer progress fields. Usage metrics tell the team when v1 can be retired safely.

Quiz Check

Quick Knowledge Test

Loading quiz questions...