Header-based versioning helps servers know which version of an API a client wants by checking special information in the request headers. This keeps URLs clean and lets clients choose versions easily.
0
0
Header-based versioning in Rest API
Introduction
When you want to keep your API URLs simple and not cluttered with version numbers.
When clients need to switch between different API versions without changing the URL.
When you want to separate version information from the resource path for better organization.
When you want to support multiple API versions at the same time without confusing URLs.
Syntax
Rest API
GET /resource HTTP/1.1
Host: api.example.com
Accept: application/vnd.example.v1+jsonThe version is specified in the Accept header or a custom header like X-API-Version.
The server reads this header to decide which version of the API to send back.
Examples
This request asks for version 1 of the API using the
Accept header.Rest API
GET /users HTTP/1.1
Host: api.example.com
Accept: application/vnd.example.v1+jsonThis request uses a custom header
X-API-Version to ask for version 2.Rest API
GET /users HTTP/1.1 Host: api.example.com X-API-Version: 2
Sample Program
This simple Flask app shows how to read a custom header X-API-Version to return different data formats for different API versions.
Rest API
from flask import Flask, request, jsonify app = Flask(__name__) @app.route('/users') def users(): version = request.headers.get('X-API-Version', '1') if version == '1': return jsonify({'users': ['Alice', 'Bob']}) elif version == '2': return jsonify({'users': [{'name': 'Alice', 'age': 30}, {'name': 'Bob', 'age': 25}]}) else: return jsonify({'error': 'Unsupported API version'}), 400 if __name__ == '__main__': app.run(debug=True)
OutputSuccess
Important Notes
Clients must include the correct header to get the right API version.
Servers should handle missing or unknown versions gracefully.
Header-based versioning keeps URLs clean but requires clients to set headers properly.
Summary
Header-based versioning uses HTTP headers to specify API versions.
This method keeps URLs simple and separates version info from resource paths.
Servers read headers like Accept or custom headers to decide response format.