Debian Codegraph @

docs/api-guide/versioning.md

raw
1 ---
2 source:
3 - versioning.py
4 ---
5
6 # Versioning
7
8 > Versioning an interface is just a "polite" way to kill deployed clients.
9 >
10 > — [Roy Fielding][cite].
11
12 API versioning allows you to alter behavior between different clients. REST framework provides for a number of different versioning schemes.
13
14 Versioning is determined by the incoming client request, and may either be based on the request URL, or based on the request headers.
15
16 There are a number of valid approaches to approaching versioning. [Non-versioned systems can also be appropriate][roy-fielding-on-versioning], particularly if you're engineering for very long-term systems with multiple clients outside of your control.
17
18 ## Versioning with REST framework
19
20 When API versioning is enabled, the `request.version` attribute will contain a string that corresponds to the version requested in the incoming client request.
21
22 By default, versioning is not enabled, and `request.version` will always return `None`.
23
24 ### Varying behavior based on the version
25
26 How you vary the API behavior is up to you, but one example you might typically want is to switch to a different serialization style in a newer version. For example:
27
28 def get_serializer_class(self):
29 if self.request.version == 'v1':
30 return AccountSerializerVersion1
31 return AccountSerializer
32
33 ### Reversing URLs for versioned APIs
34
35 The `reverse` function included by REST framework ties in with the versioning scheme. You need to make sure to include the current `request` as a keyword argument, like so.
36
37 from rest_framework.reverse import reverse
38
39 reverse('bookings-list', request=request)
40
41 The above function will apply any URL transformations appropriate to the request version. For example:
42
43 * If `NamespaceVersioning` was being used, and the API version was 'v1', then the URL lookup used would be `'v1:bookings-list'`, which might resolve to a URL like `http://example.org/v1/bookings/`.
44 * If `QueryParameterVersioning` was being used, and the API version was `1.0`, then the returned URL might be something like `http://example.org/bookings/?version=1.0`
45
46 ### Versioned APIs and hyperlinked serializers
47
48 When using hyperlinked serialization styles together with a URL based versioning scheme make sure to include the request as context to the serializer.
49
50 def get(self, request):
51 queryset = Booking.objects.all()
52 serializer = BookingsSerializer(queryset, many=True, context={'request': request})
53 return Response({'all_bookings': serializer.data})
54
55 Doing so will allow any returned URLs to include the appropriate versioning.
56
57 ## Configuring the versioning scheme
58
59 The versioning scheme is defined by the `DEFAULT_VERSIONING_CLASS` settings key.
60
61 REST_FRAMEWORK = {
62 'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.NamespaceVersioning'
63 }
64
65 Unless it is explicitly set, the value for `DEFAULT_VERSIONING_CLASS` will be `None`. In this case the `request.version` attribute will always return `None`.
66
67 You can also set the versioning scheme on an individual view. Typically you won't need to do this, as it makes more sense to have a single versioning scheme used globally. If you do need to do so, use the `versioning_class` attribute.
68
69 class ProfileList(APIView):
70 versioning_class = versioning.QueryParameterVersioning
71
72 ### Other versioning settings
73
74 The following settings keys are also used to control versioning:
75
76 * `DEFAULT_VERSION`. The value that should be used for `request.version` when no versioning information is present. Defaults to `None`.
77 * `ALLOWED_VERSIONS`. If set, this value will restrict the set of versions that may be returned by the versioning scheme, and will raise an error if the provided version is not in this set. Note that the value used for the `DEFAULT_VERSION` setting is always considered to be part of the `ALLOWED_VERSIONS` set (unless it is `None`). Defaults to `None`.
78 * `VERSION_PARAM`. The string that should be used for any versioning parameters, such as in the media type or URL query parameters. Defaults to `'version'`.
79
80 You can also set your versioning class plus those three values on a per-view or a per-viewset basis by defining your own versioning scheme and using the `default_version`, `allowed_versions` and `version_param` class variables. For example, if you want to use `URLPathVersioning`:
81
82 from rest_framework.versioning import URLPathVersioning
83 from rest_framework.views import APIView
84
85 class ExampleVersioning(URLPathVersioning):
86 default_version = ...
87 allowed_versions = ...
88 version_param = ...
89
90 class ExampleView(APIVIew):
91 versioning_class = ExampleVersioning
92
93 ---
94
95 ## API Reference
96
97 ### AcceptHeaderVersioning
98
99 This scheme requires the client to specify the version as part of the media type in the `Accept` header. The version is included as a media type parameter, that supplements the main media type.
100
101 Here's an example HTTP request using the accept header versioning style.
102
103 GET /bookings/ HTTP/1.1
104 Host: example.com
105 Accept: application/json; version=1.0
106
107 In the example request above `request.version` attribute would return the string `'1.0'`.
108
109 Versioning based on accept headers is [generally considered][klabnik-guidelines] as [best practice][heroku-guidelines], although other styles may be suitable depending on your client requirements.
110
111 #### Using accept headers with vendor media types
112
113 Strictly speaking the `json` media type is not specified as [including additional parameters][json-parameters]. If you are building a well-specified public API you might consider using a [vendor media type][vendor-media-type]. To do so, configure your renderers to use a JSON based renderer with a custom media type:
114
115 class BookingsAPIRenderer(JSONRenderer):
116 media_type = 'application/vnd.megacorp.bookings+json'
117
118 Your client requests would now look like this:
119
120 GET /bookings/ HTTP/1.1
121 Host: example.com
122 Accept: application/vnd.megacorp.bookings+json; version=1.0
123
124 ### URLPathVersioning
125
126 This scheme requires the client to specify the version as part of the URL path.
127
128 GET /v1/bookings/ HTTP/1.1
129 Host: example.com
130 Accept: application/json
131
132 Your URL conf must include a pattern that matches the version with a `'version'` keyword argument, so that this information is available to the versioning scheme.
133
134 urlpatterns = [
135 re_path(
136 r'^(?P<version>(v1|v2))/bookings/$',
137 bookings_list,
138 name='bookings-list'
139 ),
140 re_path(
141 r'^(?P<version>(v1|v2))/bookings/(?P<pk>[0-9]+)/$',
142 bookings_detail,
143 name='bookings-detail'
144 )
145 ]
146
147 ### NamespaceVersioning
148
149 To the client, this scheme is the same as `URLPathVersioning`. The only difference is how it is configured in your Django application, as it uses URL namespacing, instead of URL keyword arguments.
150
151 GET /v1/something/ HTTP/1.1
152 Host: example.com
153 Accept: application/json
154
155 With this scheme the `request.version` attribute is determined based on the `namespace` that matches the incoming request path.
156
157 In the following example we're giving a set of views two different possible URL prefixes, each under a different namespace:
158
159 # bookings/urls.py
160 urlpatterns = [
161 re_path(r'^$', bookings_list, name='bookings-list'),
162 re_path(r'^(?P<pk>[0-9]+)/$', bookings_detail, name='bookings-detail')
163 ]
164
165 # urls.py
166 urlpatterns = [
167 re_path(r'^v1/bookings/', include('bookings.urls', namespace='v1')),
168 re_path(r'^v2/bookings/', include('bookings.urls', namespace='v2'))
169 ]
170
171 Both `URLPathVersioning` and `NamespaceVersioning` are reasonable if you just need a simple versioning scheme. The `URLPathVersioning` approach might be better suitable for small ad-hoc projects, and the `NamespaceVersioning` is probably easier to manage for larger projects.
172
173 ### HostNameVersioning
174
175 The hostname versioning scheme requires the client to specify the requested version as part of the hostname in the URL.
176
177 For example the following is an HTTP request to the `http://v1.example.com/bookings/` URL:
178
179 GET /bookings/ HTTP/1.1
180 Host: v1.example.com
181 Accept: application/json
182
183 By default this implementation expects the hostname to match this simple regular expression:
184
185 ^([a-zA-Z0-9]+)\.[a-zA-Z0-9]+\.[a-zA-Z0-9]+$
186
187 Note that the first group is enclosed in brackets, indicating that this is the matched portion of the hostname.
188
189 The `HostNameVersioning` scheme can be awkward to use in debug mode as you will typically be accessing a raw IP address such as `127.0.0.1`. There are various online tutorials on how to [access localhost with a custom subdomain][lvh] which you may find helpful in this case.
190
191 Hostname based versioning can be particularly useful if you have requirements to route incoming requests to different servers based on the version, as you can configure different DNS records for different API versions.
192
193 ### QueryParameterVersioning
194
195 This scheme is a simple style that includes the version as a query parameter in the URL. For example:
196
197 GET /something/?version=0.1 HTTP/1.1
198 Host: example.com
199 Accept: application/json
200
201 ---
202
203 ## Custom versioning schemes
204
205 To implement a custom versioning scheme, subclass `BaseVersioning` and override the `.determine_version` method.
206
207 ### Example
208
209 The following example uses a custom `X-API-Version` header to determine the requested version.
210
211 class XAPIVersionScheme(versioning.BaseVersioning):
212 def determine_version(self, request, *args, **kwargs):
213 return request.META.get('HTTP_X_API_VERSION', None)
214
215 If your versioning scheme is based on the request URL, you will also want to alter how versioned URLs are determined. In order to do so you should override the `.reverse()` method on the class. See the source code for examples.
216
217 [cite]: https://www.slideshare.net/evolve_conference/201308-fielding-evolve/31
218 [roy-fielding-on-versioning]: https://www.infoq.com/articles/roy-fielding-on-versioning
219 [klabnik-guidelines]: http://blog.steveklabnik.com/posts/2011-07-03-nobody-understands-rest-or-http#i_want_my_api_to_be_versioned
220 [heroku-guidelines]: https://github.com/interagent/http-api-design/blob/master/en/foundations/require-versioning-in-the-accepts-header.md
221 [json-parameters]: https://tools.ietf.org/html/rfc4627#section-6
222 [vendor-media-type]: https://en.wikipedia.org/wiki/Internet_media_type#Vendor_tree
223 [lvh]: https://reinteractive.net/posts/199-developing-and-testing-rails-applications-with-subdomains