0
0
Rest APIprogramming~5 mins

Media type versioning in Rest API

Choose your learning style9 modes available
Introduction

Media type versioning helps servers and clients agree on which version of data format to use. It keeps APIs working smoothly when changes happen.

You want to update your API without breaking old apps.
You need to support multiple versions of your API at the same time.
You want clients to ask for a specific version of data format.
You want clear control over how data is sent and received.
You want to avoid confusion when API changes happen.
Syntax
Rest API
GET /resource HTTP/1.1
Accept: application/vnd.example.v1+json
The version is included in the media type in the Accept header.
The server reads this header to send the right version of data.
Examples
This asks for version 1 of the API data in JSON format.
Rest API
Accept: application/vnd.example.v1+json
This asks for version 2 of the API data in JSON format.
Rest API
Accept: application/vnd.example.v2+json
This header tells the server the client is sending version 1 data.
Rest API
Content-Type: application/vnd.example.v1+json
Sample Program

This simple Flask app checks the Accept header to decide which version of greeting to send back.

Rest API
from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/greeting')
def greeting():
    accept = request.headers.get('Accept', '')
    if 'vnd.example.v2+json' in accept:
        return jsonify(message='Hello from version 2!')
    elif 'vnd.example.v1+json' in accept:
        return jsonify(message='Hello from version 1!')
    else:
        return jsonify(message='Hello from default version!')

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

Always document your media type versions clearly for clients.

Use media type versioning to keep URLs clean and stable.

Clients must set the Accept header correctly to get the right version.

Summary

Media type versioning uses the Accept header to specify API version.

This helps servers send the right data format without changing URLs.

It keeps old and new clients working together smoothly.