Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

API versioning for Django! 🎯 Automatically register routes, ensure backward compatibility, and manage API versions with a simple decorator. Supports Django Rest Framework (DRF), function-based and class-based views. Stop manually defining API versions—let Django API Versioning handle it for you! 🚀

License

NotificationsYou must be signed in to change notification settings

mojtaba-arvin/django-api-versioning

Repository files navigation

PyPI versionBuild StatuscodecovLicense: MIT

Django API Versioning is a powerful and flexible library for managingAPI versioning in Django projects. It allows you to easily define and manage different versions of your API endpoints using decorators, ensuring backward compatibility and clean code organization.

Features

  • Easy Versioning: Define API versions using simple decorators.
  • Backward Compatibility: Automatically register routes for all versions up to the specified version.
  • Automatic Registration: Views areautomatically registered for each version specified, so there is no need to manually register each version in yoururls.py.
  • Customizable Settings: Configure API base path, minimum and maximum versions, and more.
  • Type Checking: Full support for type hints and static type checking withmypy.
  • Testing Ready: Includes comprehensive test suite and pre-commit hooks for code quality.

Installation

You caninstall Django API Versioning via pip:

pip install django-api-versioning

Quick Start

  1. Add to Django Settings:

INSTALLED_APPS= [    ...'django_api_versioning',    ...]
  1. Define API Settings:

API_BASE_PATH="api/v{version}/"API_MIN_VERSION=1API_MAX_VERSION=3
  1. Register API urls:

if you don't use anyROOT_URLCONF in settings you can use this:

ROOT_URLCONF='django_api_versioning.urls'

or you have already have aROOT_URLCONF in settings, you only need to import them into your rooturls.py:

fromdjango.urlsimportpath,includefromdjango_api_versioning.urlsimporturlpatternsasapi_urlpatternsurlpatterns= [# other paths here# use empty `route` param and use `API_BASE_PATH` in settings as prefixpath('',include(api_urlpatterns)),   ]
  1. Use the Decorator:

Theendpoint decorator can be used in both function-based views (FBVs) and class-based views (CBVs). It's also fully compatible withDjango Rest Framework (DRF). The decorator allows you to define versioning for your API views and supports backward compatibility by default and you don't need to passbackward=True flag to theendpoint decorator.

Example for Function-Based Views (FBVs):

fromdjango_api_versioning.decoratorsimportendpointfromdjango.httpimportHttpResponse@endpoint("users",version=2,app_name='account_app',view_name="users_list_api")defusers_view(request):returnHttpResponse("API Version 2 Users")

In this example, theusers_view function is decorated with the endpoint decorator. This specifies that the view is accessible under version2 of the API andsupports backward compatibility. Thebackward=True flag as default ensures that users can also access the previous version (version1) at/api/v1/account_app/users.

api/v1/account_app/users [name='users_list_api']api/v2/account_app/users [name='users_list_api']

Example for Class-Based Views (CBVs):

For class-based views, you can apply the decorator to methods such asget,post, or any other HTTP method you need to handle. Here’s an example:

fromdjango_api_versioning.decoratorsimportendpointfromdjango.httpimportJsonResponsefromdjango.viewsimportView@endpoint("users",version=2,app_name='account_app',view_name="users_list_api")classUsersView(View):defget(self,request):returnJsonResponse({"message":"API Version 2 Users"})

Integration with Django Rest Framework (DRF):

If you have already installedDjango Rest Framework, theendpoint decorator can be easily applied to APIView or viewsets. Here’s an example with a DRF APIView:

fromrest_framework.viewsimportAPIViewfromrest_framework.permissionsimportAllowAnyfromrest_framework.responseimportResponsefromdjango_api_versioning.decoratorsimportendpoint@endpoint("users",version=2,app_name='account_app',view_name="users_list_api")classUsersAPIView(APIView):permission_classes= [AllowAny]defget(self,request):returnResponse({"message":"API Version 2 Users"})

URL Generation Based on Versioning:

Once the decorator is applied, the URLs for your API will be generated based on the version specified in the decorator. For example, if theAPI_MIN_VERSION in yoursettings.py is set to1 and the version in the decorator is set to2, the following URLs will be available:

api/v1/account_app/users [name='users_list_api']api/v2/account_app/users [name='users_list_api']

TheAPI_MIN_VERSION setting ensures that users can access the API using different versions, providing backward compatibility. You can adjust which versions are considered valid by modifying theAPI_MIN_VERSION andversion numbers in the decorators.

Additional Configuration Options:

Withoutapp_name: If you don't passapp_name in the decorator, like this:

@endpoint("users",version=2,view_name="users_list_api")

The generated URLs will be:

api/v1/users [name='users_list_api']api/v2/users [name='users_list_api']

Withoutversion: If you don't passversion in the decorator, like this:

@endpoint("users",view_name="users_list_api")

API versioning will be disabled (API_BASE_PATH as prefix will be removed) for that view. The only URL generated will be:

users [name='users_list_api']

Settingbackward=False: By default, thebackward parameter is set toTrue, which ensures backward compatibility. If you explicitly setbackward=False, like this:

@endpoint("users",version=2,backward=False,view_name="users_list_api")

The generated URL will be only version 2:

api/v2/users [name='users_list_api']
  1. Run the Server:
python manage.py runserver

Notes

1.API_BASE_PATH in settings Must Include ‍‍{version}:

TheAPI_BASE_PATH should always include{version} to ensure proper API versioning. This is important for correctly mapping API routes to different versions.

2. Usingapp_name in theendpoint decorator:

It's recommended to fill in theapp_name in theendpoint decorator to make the API URLsmore unique and organized. This ensures that the routes are scoped under the correct app, avoiding potential conflicts and making them easier to manage.

3. Behavior When Resolving a Route:

When resolving the route using Django'sreverse() function or any other method to resolve the URL, the latest version (highest version number) of the API will be returned. In this example, route for version 3 would be resolved:

fromdjango_api_versioning.decoratorsimportendpointfromdjango.httpimportJsonResponsefromdjango.viewsimportViewfromdjango.urlsimportreverse@endpoint("users",version=3,app_name='account_app',view_name="users_list_api")classUsersView(View):defget(self,request):returnJsonResponse({"path of users_list_api view is":reverse('users_list_api')})

response body:

{"path of users_list_api view is":"api/v3/account_app/users" }

The generated URLs will be:

api/v1/account_app/users [name='users_list_api']api/v2/account_app/users [name='users_list_api']api/v3/account_app/users [name='users_list_api']

4. Views with Version Less ThanAPI_MIN_VERSION Are Automatically Ignored:

Any view whoseversion is less than theAPI_MIN_VERSION will be automatically ignored. This means clients will no longer have access to these older versions,without the need to manually edit or remove code. This is handled automatically by the package.

5. URLs for Versions BetweenAPI_MIN_VERSION <=version <=API_MAX_VERSION:

Endpoints that have versions within the range defined byAPI_MIN_VERSION <=version <=API_MAX_VERSION will always have a corresponding URL generated. This ensures that only valid versions will be accessible, providing flexibility in version management.

endpoint Decorator Function Definition

Theendpoint decorator is designed to register API views with versioning support in a Django application. It provides flexibility in managing versioned endpoints and ensures backward compatibility with previous versions of the API.

defendpoint(postfix:str,version:Optional[int]=None,backward:bool=True,app_name:Optional[str]=None,view_name:Optional[str]=None,)->Callable:"""    Decorator to register API views with versioning support.    - Uses `API_MIN_VERSION` and `API_MAX_VERSION` from Django settings.    - Supports backward compatibility by registering multiple versions if needed.    - Ensures that no version lower than `API_MIN_VERSION` is registered.    Args:        postfix (str): The endpoint suffix (e.g., "users" → "api/v1/users").        version (Optional[int]): The version of the API. Defaults to None (unversioned).        backward (bool): If True, registers routes for all versions from `API_MIN_VERSION` up to the current version, which is less than or equal to `API_MAX_VERSION`. Defaults to True.        app_name (Optional[str]): The app name to be prefixed to the route.        view_name (Optional[str]): The custom view name for Django.    Returns:        Callable: The decorated view function.    Raises:        VersionTypeError: If the provided `version` is not an integer.        VersionRangeError: If `API_MIN_VERSION` or `API_MAX_VERSION` are not properly set.    """

Contributing

Feel free to open an issue or submit a pull request with any improvements or bug fixes. We appreciate contributions to enhance this package!

License

This package is open-source and available under the MIT license.

About

API versioning for Django! 🎯 Automatically register routes, ensure backward compatibility, and manage API versions with a simple decorator. Supports Django Rest Framework (DRF), function-based and class-based views. Stop manually defining API versions—let Django API Versioning handle it for you! 🚀

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp