SoFunction
Updated on 2024-11-21

Django interface version control

I. Preface

existRESTfulIn the specification, questions about versioning withrestfulWhen the specification does open interfaces, the user requestsAPIThe system returns data. But inevitably in the process of system development, the inevitable need to add new resources, or modify existing resources. Therefore, changes and upgrades are essential, but, as a platform developer, you should know: once theAPIOpen it up, someone starts using it, and any changes to the platform need to consider the impact on current users. Therefore, to make an open platform, from the firstAPIThe design will need to startAPIthe issue of version control policies.APIThe version control policy is like a long-term agreement between the open platform and the users of the platform, the design of which will directly determine whether the users will use the platform or not, or whether the users will abandon the platform after using it because of a certain version upgrade.

II. Configuration

There are two configuration options, asettingsis configured globally in the view, and the second is specified in the view, though theThis method is not normally usedBecause version control is for the most part a global processing situation

2.1 Global configuration

REST_FRAMEWORK = {
    'DEFAULT_VERSIONING_CLASS': None,
    'DEFAULT_VERSION': None,
    'ALLOWED_VERSIONS': None,
    'VERSION_PARAM': 'version',
}
  • DEFAULT_VERSIONING_CLASS: Specify the version controlled class, e.g. 'rest_framework.' in various ways. Default is None, when it is None, the framework variable will always return None
  • DEFAULT_VERSION: default value used to set when version control information does not exist, default setting is None.
  • ALLOWED_VERSIONS: allowed version numbers, e.g. ['v1', 'v2']. Case sensitive, if the requested version number is not in this list, an error is thrown, the value of DEFAULT_VERSION above must be one of the values in the list, except None.
  • VERSION_PARAM: version control parameter string, the default is version, generally do not modify the

2.2. View Configuration

# Specify only the version control class
class ProfileList(APIView):
    # Specify the version control class
    versioning_class = 

Third, drf built-in 5 version control class

3.1、AcceptHeaderVersioning

Version control based on request headers, which is also the most recommended approach

3.1.1, http access method

GET /bookings/ HTTP/1.1

Host:

Accept: application/json; version=1.0

In the example request aboveproperty will return the string '1.0'. Based on theaccept headers version control is generally considered best practice, although other methods of version control may be appropriate for your client's needs.

3.1.2、settings

REST_FRAMEWORK = {
	'DEFAULT_VERSIONING_CLASS': 'rest_framework.',
        'DEFAULT_VERSION': 'v1',
        'ALLOWED_VERSIONS': ['v1', 'v2'],
}

Description:

  • Set the version control class toAcceptHeaderVersioning
  • Not detected.versionWhen the default isv1releases
  • The 2 allowed version models are:['v1', 'v2']

3.1.3、serializers

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


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

Description:

  • Depending on the version number, theresponseThe return content is controlled, and we set 2 differentBookmodelingserializerclass corresponds to a different version
  • The 2 serialization classes return different fields
  • BookSerializerV2 (used form a nominal expression)fieldsdoes not contain theimage , then the attribute definition should be removed, otherwise it will throw an error

3.1.4、views

class BookView(ListAPIView):
    queryset = ()
    serializer_class = BookSerializer

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

Description:

  • modificationsBookViewclass, overloading theget_serializer_classmethodologies
  • pass (a bill or inspection etc) Getting the captured version number for control

3.1.5.

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

We add fields to the request headerAccept:application/json;version=v2and it will returnBookSerializerV2serialized fields, i.e., there is noimagefield

3.2、URLPathVersioning

This scheme 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

Host:

Accept: application/json

Description:

Version control appears in theurlpath, but specifically this v1 The section in which it appears depends on theurlThe situation in the routing configuration

3.2.2、settings

REST_FRAMEWORK = {
	'DEFAULT_VERSIONING_CLASS': 'rest_framework.',
        'DEFAULT_VERSION': 'v1',
        'ALLOWED_VERSIONS': ['v1', 'v2'],
}

3.2.3、urls

Sub-application of the center:

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

Description:

To set version control at the end, access theurlIt's similar:http://127.0.0.1:8000/api/v2/books/

3.2.4. Visits

We are configuring theurlafterurlEntering v1 in will access the v1 version of the interface

existurlEntering v2 in will access the v2 version of the interface

3.3、NamespaceVersioning

For clients, this solution is similar to theURLPathVersioningSame. The only difference is how it is inDjango configured in the application because it uses theURL confInstead of the namespace in theURL confThe keyword argument in the

Using this program, theattribute is based on a path that matches the incoming request'snamespace Determined.

If you just need a simple version control solutionURLPathVersioningcap (a poem)NamespaceVersioningIt's all appropriate.URLPathVersioningThis approach may be better suited for smaller projects and for larger projectsNamespaceVersioningIt may be more manageable.

3.3.1. http access method

GET v1/something/ HTTP/1.1

Host:

3.3.2、settings

REST_FRAMEWORK = {
	'DEFAULT_VERSIONING_CLASS': 'rest_framework.',
        'DEFAULT_VERSION': 'v1',
        'ALLOWED_VERSIONS': ['v1', 'v2'],
}

3.3.3、urls

In the root:

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

Description:

Added 2v1cap (a poem)v2The different routing configurations of the

3.3.4. Visits

interviewsv1releases

interviewsv2releases

the restHostNameVersioningcap (a poem)QueryParameterVersioningNot used much, you can check the official documentation if you want to know more.

Above is the analysis of Django interface version control of the details , more information about Django interface version control please pay attention to my other related articles !