File: api_versioning.rst

package info (click to toggle)
flask-rebar 3.4.0-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 15,852 kB
  • sloc: python: 9,539; javascript: 20; makefile: 16
file content (67 lines) | stat: -rw-r--r-- 1,862 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
API Versioning
--------------

URL Prefixing
=============

There are many ways to do API versioning. Flask-Rebar encourages a simple and very common approach - URL prefixing.

.. code-block:: python

   from flask import Flask
   from flask_rebar import Rebar


   rebar = Rebar()
   v1_registry = rebar.create_handler_registry(prefix='/v1')
   v2_registry = rebar.create_handler_registry(prefix='/v2')

   @v1_registry.handles(rule='/foos')
   @v2_registry.handles(rule='/foos')
   def get_foos():
       ...

   @v1_registry.handles(rule='/bar')
   def get_bars():
       ...

   @v2_registry.handles(rule='/bar')
   def get_bars():
       ...

   app = Flask(__name__)
   rebar.init_app(app)

Here we have two registries, and both get registered when calling ``rebar.init_app``.

The same handler function can be used for multiple registries.

This will produce a separate Swagger specification and UI instance per API version, which Flask-Rebar encourages for better support with tools like `swagger-codegen <https://github.com/swagger-api/swagger-codegen>`_.


Cloning a Registry
==================

While its recommended to start versioning an API from the get go, sometimes we don't. In that case, it's a common practice to assume that no version prefix is the same as version 1 of the API in order to maintain backwards compatibility for clients that might already be calling non-prefixed endpoints.

Flask-Rebar supports copying an entire registry and changing the URL prefix:

.. code-block:: python

   from flask import Flask
   from flask_rebar import Rebar


   rebar = Rebar()
   registry = rebar.create_handler_registry()

   @registry.handles(rule='/foos')
   def get_foos():
       ...

   v1_registry = registry.clone()
   v1_registry.prefix = '/v1'
   rebar.add_handler_registry(v1_registry)

   app = Flask(__name__)
   rebar.init_app(app)