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- wherev{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/123Example
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 versioningQuick Reference
| Aspect | Description |
|---|---|
| Version location | In the URI path as a segment (e.g., /v1/) |
| Version format | Usually 'v' followed by a number (v1, v2, v3) |
| Client usage | Specify version by calling the correct URI |
| Advantages | Simple, visible, easy to cache and debug |
| Disadvantages | Requires 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.