Analysis of Django interface version control

  • 1、 Foreword
  • 2、 Disposition
    • 2.1. Global configuration
    • 2.2. View configuration
  • 3、 Five version control classes built in DRF
    • 3.1、AcceptHeaderVersioning
      • 3.1.1. HTTP access method
      • 3.1.2、settings
      • 3.1.3、serializers
      • 3.1.4、views
      • 3.1.5 access
    • 3.2、URLPathVersioning
      • 3.2.1. HTTP access method
      • 3.2.2、settings
      • 3.2.3、urls
      • 3.2.4 access
    • 3.3、NamespaceVersioning
      • 3.3.1. HTTP access method
      • 3.3.2、settings
      • 3.3.3、urls
      • 3.3.4 access

1、 Foreword

stayRESTfulIn the specification, for problems related to version, userestfulWhen the specification makes an open interface, the user requestsAPI, the system returns data. However, in the process of system development, it is inevitable to add new resources or modify existing resources. Therefore, changes and upgrades are essential. However, as a platform developer, you should know that onceAPIAfter opening up, someone began to use it. Any change to the platform needs to consider the impact on current users. Therefore, make an open platform from the firstAPIYour design needs to startAPIVersion control policy issues,APIThe version control strategy of is like a long-term agreement between the open platform and platform users. Its design will directly determine whether users use the platform, or whether users will directly abandon the platform because of a version upgrade.

2、 Disposition

There are two configuration schemes, one is insettingsThe second is to specify in the view, butThis method is generally not usedBecause version control is a global process in most cases

2.1. Global configuration

    'VERSION_PARAM': 'version',
  • DEFAULT_ VERSIONING_ Class: Specifies the version control class, for example: ‘rest’_ framework. versioning. Namespace versioning ‘, there are many ways. The default is none. When it is none, the frame variable request Version will always return none
  • DEFAULT_ Version: used to set request when version control information does not exist The default value of version is none by default.
  • ALLOWED_ Versions: allowed version number, for example: [‘v1 ‘,’ V2 ‘]. Case sensitive. If the requested version number is not in this list, an error will be thrown, and the above default_ The value of version must be the value in the list, except none
  • VERSION_ Param: the string of version control parameters. The default is version. It is generally not modified

2.2. View configuration

#Specify only version control classes    
class ProfileList(APIView):
    #Specify version control class
    versioning_class = versioning.QueryParameterVersioning

3、 Five version control classes built in DRF


Version control based on request header is also the most recommended method

3.1.1. HTTP access method

GET /bookings/ HTTP/1.1


Accept: application/json; version=1.0

In the example request aboverequest.versionProperty will return the string ‘1.0’. be based onaccept headers Versioning is often considered a best practice, although other versioning methods may suit your client needs.


	'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.AcceptHeaderVersioning',
        'DEFAULT_VERSION': 'v1',
        'ALLOWED_VERSIONS': ['v1', 'v2'],


  • Set version control class toAcceptHeaderVersioning
  • Not detectedversionThe default isv1edition
  • The two versions allowed are:['v1', 'v2']


class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = BookInfo
        fields = ['title', 'pub_date', 'read', 'comment', 'image']

class BookSerializerV2(serializers.ModelSerializer):
    class Meta:
        model = BookInfo
        fields = ['title', 'pub_date', 'read', 'comment']


  • According to different version numbers, you canresponseReturn content for control, we set 2 differentBookModelledserializerClass corresponds to different versions
  • The fields returned by the two serialization classes are different
  • BookSerializerV2offieldsNot included inimage, then the attribute definition should be removed, or an error will be thrown


class BookView(ListAPIView):
    queryset = BookInfo.objects.all()
    serializer_class = BookSerializer

    def get_serializer_class(self):
        if self.request.version == "v2":
            return BookSerializerV2
        return self.serializer_class


  • modifyBookViewClass, overloadingget_serializer_classmethod
  • adoptself.request.version Get the captured version number for control

3.1.5 access

We add fields to the request headerAccept:application/json;version=v1, it will returnBookSerializerSerialized fields, that is, there areimagefield

We add fields to the request headerAccept:application/json;version=v2, it will returnBookSerializerV2Serialized fields, that is, noimagefield


This scenario requires the client to specify the version as part of the URL path.

3.2.1. HTTP access method

GET /v1/bookings/ HTTP/1.1


Accept: application/json


Version control appears inurlIn the path, but the specific one v1Which part appears depends onurlSituation in routing configuration


	'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.URLPathVersioning',
        'DEFAULT_VERSION': 'v1',
        'ALLOWED_VERSIONS': ['v1', 'v2'],


URLs for subapplications Py:

urlpatterns = [
    path('<str:version>/books/', views.BookView.as_view()),


Set version control at the end, accessurlIs similar to:

3.2.4 access

We’re configuringurlAfter, inurlIf you enter V1 in, you will access the V1 version of the interface

stayurlIf you enter V2 in, you will access the V2 version of the interface


For clients, this scheme is similar toURLPathVersioningSame. The only difference is how it worksDjangoConfigured in the application because it usesURL confNamespace in instead ofURL confKeyword parameters in.

Using this scheme,request.versionProperty is based on the path that matches the incoming requestnamespaceaffirmatory.

If you only need a simple version control schemeURLPathVersioningandNamespaceVersioningAre appropriate.URLPathVersioningThis approach may be more suitable for small projects and for larger projectsNamespaceVersioningIt may be easier to manage.

3.3.1. HTTP access method

GET v1/something/ HTTP/1.1



	'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.NamespaceVersioning',
        'DEFAULT_VERSION': 'v1',
        'ALLOWED_VERSIONS': ['v1', 'v2'],


Root URLs Py:

urlpatterns = [
    path('v1/api/', include('api.urls', namespace='v1')),
    path('v2/api/', include('api.urls', namespace='v2')),


Added 2v1andv2Different routing configurations

3.3.4 access



restHostNameVersioningandQueryParameterVersioningI don’t use much. If you want to know, you can check the official documents

The above is the detailed analysis of Django interface version control. For more information about Django interface version control, please pay attention to other relevant articles of developeppaer!