0
0
Rest-apiHow-ToBeginner ยท 4 min read

How to Use URI Versioning in REST APIs

URI versioning is done by including the API version number directly in the URI path, such as /v1/resource. This approach clearly separates versions and makes it easy for clients to specify which API version they want to use.
๐Ÿ“

Syntax

URI versioning places the version number as a segment in the API path. The general pattern is:

  • /v{version_number}/resource - where v{version_number} is the version identifier.
  • The version is usually a number like v1, v2, etc.
  • This version segment comes right after the domain and before the resource path.
plaintext
/v1/users
/v2/orders
/v3/products/123
๐Ÿ’ป

Example

This example shows a simple REST API endpoint using URI versioning. The client requests version 1 or version 2 of the /items resource.

python
from flask import Flask, jsonify, request

app = Flask(__name__)

@app.route('/v1/items')
def items_v1():
    # Version 1 returns a simple list of item names
    return jsonify({'version': 'v1', 'items': ['apple', 'banana', 'cherry']})

@app.route('/v2/items')
def items_v2():
    # Version 2 returns items with prices
    return jsonify({'version': 'v2', 'items': [
        {'name': 'apple', 'price': 0.5},
        {'name': 'banana', 'price': 0.3},
        {'name': 'cherry', 'price': 0.2}
    ]})

if __name__ == '__main__':
    app.run(debug=True)
Output
Running the Flask app and visiting http://localhost:5000/v1/items returns: {"version":"v1","items":["apple","banana","cherry"]} Visiting http://localhost:5000/v2/items returns: {"version":"v2","items":[{"name":"apple","price":0.5},{"name":"banana","price":0.3},{"name":"cherry","price":0.2}]}
โš ๏ธ

Common Pitfalls

  • Mixing versioning methods: Avoid combining URI versioning with header or query parameter versioning as it confuses clients.
  • Hardcoding versions: Make sure your server routes clearly separate versions to avoid accidental breaking changes.
  • Ignoring backward compatibility: Always maintain older versions until clients migrate to newer ones.
plaintext
Wrong approach:
GET /items?version=1  # Using query parameter versioning mixed with URI

Right approach:
GET /v1/items  # Clear URI versioning
๐Ÿ“Š

Quick Reference

AspectDescription
Version locationIn the URI path as a segment (e.g., /v1/)
Version formatUsually 'v' followed by a number (v1, v2, v3)
Client usageSpecify version by calling the correct URI
AdvantagesSimple, visible, easy to cache and debug
DisadvantagesRequires new endpoints for each version
โœ…

Key Takeaways

Place the version number in the URI path to clearly separate API versions.
Use a consistent format like /v1/, /v2/ to keep versioning clear and simple.
Avoid mixing URI versioning with other versioning methods to prevent confusion.
Maintain backward compatibility by keeping old versions active until clients upgrade.
URI versioning makes it easy for clients and servers to manage multiple API versions.