0
0
Rest APIprogramming~5 mins

Query parameter versioning in Rest API

Choose your learning style9 modes available
Introduction

Query parameter versioning helps you manage different versions of an API by adding a version number in the URL query. This way, clients can ask for the version they want.

When you want to keep old API versions working while adding new features.
When clients need to choose which API version to use without changing the URL path.
When you want a simple way to test new API versions without breaking existing users.
Syntax
Rest API
GET /api/resource?version=1
GET /api/resource?version=2

The version is passed as a query parameter, usually named version.

This method keeps the base URL the same and only changes the query part.

Examples
Request users using version 1 of the API.
Rest API
GET /users?version=1
Request users using version 2 of the API with new features.
Rest API
GET /users?version=2
Request products list from version 1.
Rest API
GET /products?version=1
Sample Program

This simple Flask app shows how to use query parameter versioning. It checks the version parameter and returns different data based on it.

Rest API
from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/api/data')
def get_data():
    version = request.args.get('version', '1')
    if version == '1':
        return jsonify({'message': 'This is version 1 data'})
    elif version == '2':
        return jsonify({'message': 'This is version 2 data with extra info', 'extra': 123})
    else:
        return jsonify({'error': 'Version not supported'}), 400

if __name__ == '__main__':
    app.run(debug=True)
OutputSuccess
Important Notes

Query parameter versioning is easy to implement but can clutter URLs if many parameters are used.

Clients must remember to add the version parameter to get the right API version.

It works well when you want to keep the URL path clean and use parameters for version control.

Summary

Query parameter versioning uses a URL query like ?version=1 to select API versions.

It helps keep old and new API versions available without changing the main URL path.

Clients specify the version they want by adding the version number in the query string.