Generate Views, Serializers, and Urls for your Django Rest Framework application

Overview

DRF Generators

Writing APIs can be boring and repetitive work. Don't write another CRUDdy view in Django Rest Framework. With DRF Generators, one simple command will generate all of your Views, Serializers, and even Urls for your Django Rest Framework application!

For a full step-by-step tutorial, check out my blog post!

This is not intended to give you a production quality API. It was intended to jumpstart your development and save you from writing the same code over and over for each model.


Supported Python versions Latest Version License Travis CI Django 1.11, 2.2, 3.0 DRF 3.11



Installation

Install with pip:

$ pip install drf-generators

or Clone the repo and install manually:

$ git clone https://github.com/brobin/drf-generators.git
$ cd drf-generators
$ python setup.py install

To use DRF Generators, add it your INSTALLED_APPS.

INSTALLED_APPS = (
    ...
    'rest_framework',
    'drf_generators',
    ...
)

Note: In order to use the APIView classes, you must have the rest framework DEFAULT_PAGINATION_CLASS and PAGE_SIZE set.

REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 15
}

Usage

To use the generators, run the following command, where app is the application to generate an API for.

$ python manage.py generate {app} {options}
Option Action
--serializers Generate only Serializers for your app.
--views Generate only Views for your app.
--urls Generate only urls for your app.
--force Overwrite existing files without the warning prompt.
-f, --format Format to use when generating views and urls. Valid options: viewset, apiview, function, modelviewset. Default: viewset.
-d, --depth Serialization depth for related models. Default: 0

Example: Generate everything for the app api with function style views, overwriting existing files, with a serialization depth of 2.

$ python manage.py generate api --format function --force --depth=2

Serializers

Drf Generators will create serializers.py for your application. It currently uses rest framework's ModelSerializer for serialization of the models defined in models.py.

class ModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = User

Views

DRF Generators will create views.py for your application. It can generate ViewSet, APIView and function based views. Set the --format option when running the generator to pick the preferred style

ViewSet

python manage.py generate api --format viewset

class ModelViewSet(ViewSet):

    def list(self, request):
        ...
    def create(self, request):
        ...
    def retrieve(self, request, pk=None):
        ...
    def update(self, request, pk=None):
        ...
    def destroy(self, request, pk=None):
        ...

APIView

python manage.py generate api --format apiview

class ModelAPIView(APIView):

    def get(self, request, id, format=None):
        ...
    def put(self, request, id, format=None):
        ...
    def delete(self, request, id, format=None):
        ...

class ModelAPIListView(APIView):

    def get(self, request, format=None):
        ...
    def post(self, request, format=None):
        ...

Function

python manage.py generate api --format function

@api_view(['GET', 'POST'])
def model_list(request):
    if request.method == 'GET':
        ...
    elif request.method == 'POST':
        ...

@api_view(['GET', 'PUT', 'DELETE'])
def model_detail(request, pk):
    if request.method == 'GET':
        ...
    elif request.method == 'PUT':
        ...
    elif request.method == 'DELETE':
        ...

ModelViewSet

python manage.py generate api --format modelviewset

class MyModelViewSet(ModelViewSet):
    queryset = MyModel.objects.all()
    serializer_class = MyModelSerializer

Urls

Finally, DRF Generator will create you a default urls.py to match the View format you are using.

ViewSet & ModeViewSet Routes

router = SimpleRouter()

router.register(r'model', views.ModelViewSet, 'Model')

urlpatterns = router.urls

APIView urls

url(r'^model/([0-9]+)$', views.ModelAPIView.as_view()),
url(r'^model', views.ModelAPIListView.as_view()),

Function urls

urlpatterns = [

    url(r'^model/(?P
   
    [0-9]+)$'
   , views.model_detail),
    url(r'^model/$', views.model_list),

]

urlpatterns = format_suffix_patterns(urlpatterns)

Tests

A full application built with drf-generators can be found in the tests directory. Instructions on running the tests can be found in the test project's README.

License

MIT License. See LICENSE.

Comments
  • add exclude = () for DRF 3.3 compatability

    add exclude = () for DRF 3.3 compatability

    "Serializers must include either a fields option, or an exclude option." source: http://www.django-rest-framework.org/topics/3.5-announcement/#modelserializer-fields-and-exclude

    alternate solutions proposed here: https://github.com/Brobin/drf-generators/pull/26

    opened by resalisbury 9
  • Django 2.0 compatibility, and better Python 3 support

    Django 2.0 compatibility, and better Python 3 support

    I made some changes to support Django 2.0 and added a few things to improve python 3 support. Please test with your test runners to make sure I haven't broken any older functionality, as I tested the best I could. Thanks!

    opened by jnegro 7
  • File missing from pip install

    File missing from pip install

    Hi there.

    The file <path-to-python-site-packages>/drf_generators/management/__init__.py is missing when installing drf-generators from pip, as described at http://brobin.me/blog/2015/4/13/how-to-quickly-write-an-api-in-django

    This produces the following error:

    $ python manage.py generate api --format modelviewset
    Traceback (most recent call last):
      File "manage.py", line 10, in <module>
        execute_from_command_line(sys.argv)
      File "/home/user/django-app/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
        utility.execute()
      File "/home/user/django-app/lib/python2.7/site-packages/django/core/management/__init__.py", line 330, in execute
        self.fetch_command(subcommand).run_from_argv(self.argv)
      File "/home/user/django-app/lib/python2.7/site-packages/django/core/management/__init__.py", line 190, in fetch_command
        klass = load_command_class(app_name, subcommand)
      File "/home/user/django-app/lib/python2.7/site-packages/django/core/management/__init__.py", line 40, in load_command_class
        module = import_module('%s.management.commands.%s' % (app_name, name))
      File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
        __import__(name)
    ImportError: No module named management.commands.generate
    

    It appears easily fixed by:

    touch <path-to-python-site-packages>/drf_generators/management/__init__.py
    

    After this, running python manage.py generate api --format modelviewset seems to run without any problems.

    opened by austinjp 5
  • Django 1.10 support. 'AppCommand' has no attribute 'option_list'

    Django 1.10 support. 'AppCommand' has no attribute 'option_list'

    when I run this command this gives error. AttributeError: type object 'AppCommand' has no attribute 'option_list'

    :( that's why http://127.0.0.1:8000/ gives me page not found

    enhancement help wanted 
    opened by KiranPrajapati345 4
  •  'AppCommand' has no attribute 'option_list'

    'AppCommand' has no attribute 'option_list'

    I'm attempting to run the generator for app named "manager"

    python manage.py generate manager --format modelviewset

    I'm getting the following error

      File "/python/api/lib/python3.5/site-packages/drf_generators/management/commands/generate.py", line 8, in <module>
        class Command(AppCommand):
      File "python/api/lib/python3.5/site-packages/drf_generators/management/commands/generate.py", line 33, in Command
        option_list = AppCommand.option_list + base_options
    AttributeError: type object 'AppCommand' has no attribute 'option_list'
    
    duplicate 
    opened by DeanKamali 4
  • final touch

    final touch

    that appeared after all what i have done

    Using the URLconf defined in example_api.urls, Django tried these URL patterns, in this order:

    ^admin/
    ^api/
    

    The empty path didn't match any of these

    opened by ahmedjemmy 3
  • Some small fixes

    Some small fixes

    I discovered drf-generators today, I'm very impressed! It's a very cool project and works very well to kickstart your API and save you from a lot of repetitive typing. Thanks a lot! :)

    opened by jeverling 3
  • added compatibility with django 2.X

    added compatibility with django 2.X

    I've just edited the version check to accept Django versions 2.0 or higher (but not for eventually Django 3.X or higher), everything seems to works fine

    opened by eathtespagheti 2
  • add fields = '__all__' to serializer template

    add fields = '__all__' to serializer template

    ModelSerializer and HyperlinkedModelSerializer must include either a fields option, or an exclude option. The fields = 'all' shortcut may be used to explicitly include all fields.

    Failing to set either fields or exclude raised a pending deprecation warning in version 3.3 and raised a deprecation warning in 3.4. Its usage is now mandatory.

    http://www.django-rest-framework.org/topics/3.5-announcement/#modelserializer-fields-and-exclude

    opened by resalisbury 2
  • Add Permission classes to Views

    Add Permission classes to Views

    Add default authentication to views.

    Example for viewset, modelviewset, apiview

    from rest_framework import permissions
    
    class SomeViewSet(SomeViewType):
        permission_classes = (permissions.SomePermission,)
    

    Example for function based

    @permission_classes(permissions.SomePermission,)
    def some_veiw():
        ...
    
    enhancement feature 
    opened by Brobin 2
  • Add Authentication classes to Views

    Add Authentication classes to Views

    Add default authentication to views.

    Example for viewset, modelviewset, apiview

    from rest_framework import authentication, permissions
    
    class SomeViewSet(SomeViewType):
        authentication_classes = (authentication.TokenAuthentication,)
    

    Example for function based

    @authentication_classes(...)
    def some_veiw():
        ...
    
    enhancement feature 
    opened by Brobin 2
  • [help wanted] Is is possible to set view restriction in models?

    [help wanted] Is is possible to set view restriction in models?

    Hello there - I just found this AMAZING repo and it works wonders of initializing a pretty comprehensive start for a fully covering api!

    I have quite a few models that are read-only, and I was wondering if it is possible to define this somewhere, such the irrelevant properties in views and serializers are not set?

    opened by jakob1379 0
  • Add support for generating an API from a different app

    Add support for generating an API from a different app

    I have a well-established Django app with its models.py and other bits in an app called schema. I started developing an API in a different app called api but didn't get far. Then I discovered this amazing project! Is there a way to make it write out the generated API files in a different app from the source app? Thanks

    opened by djjudas21 0
  • Option for printing to stdout instead of wrting to file

    Option for printing to stdout instead of wrting to file

    Instead of writing / overwriting a file, I would like an option to print to stdout.

    It would let the user decide to pipe the output to another file, or copy just parts of the output, without worrying about overwriting existing files.

    opened by mfit 0
  • Travis-ci: added support for ppc64le along with amd64

    Travis-ci: added support for ppc64le along with amd64

    Hi, I have added support for ppc64le build on travis-ci in the branch . The travis-ci build log can be tracked on the link :https://travis-ci.com/github/sanjaymsh/drf-generators/builds/187429863 . I believe it is ready for the final review and merge. Please have a look on it and if everything looks fine for you then please approve it for merge.

    Thanks !!

    opened by sanjaymsh 1
Releases(0.5.0)
  • 0.5.0(Feb 5, 2020)

    • Now supports both LTS versions of Django as well as 3.0
    • Updated test matrix for DRF 3.11
    • Updated test matrix for Python 3.6, 3.7, 3.8
    • Updated URLs for the new path syntax
    Source code(tar.gz)
    Source code(zip)
  • 0.2.8(Feb 5, 2016)

  • 0.2.7(Oct 13, 2015)

  • 0.2.6(Sep 20, 2015)

  • 0.2.5(Aug 24, 2015)

    Minor fixes

    • Only include depth in serializers when >0, "modelviewset" in format list - jeverling
    • Removed blank lines from start/end of files and unused imports - jeverling
    Source code(tar.gz)
    Source code(zip)
  • 0.2.4(Apr 30, 2015)

  • 0.2.3(Apr 19, 2015)

  • 0.2.2(Apr 11, 2015)

  • 0.2.1(Apr 10, 2015)

  • 0.2(Apr 9, 2015)

    Features

    • function based views are now supported
    • --force option added to overwrite files
    • added test api for function based views
    • --format option added for view format. viewset by default

    Style Changes

    • moved templates to separate files for each view style

    Bugfixes

    • fixed input and raw_input for python 2 and python 3
    Source code(tar.gz)
    Source code(zip)
  • 0.1.6(Apr 8, 2015)

    I had to iron out a few bugs (including input vs raw_input) for the differences between Python 2.7 and 3.4, but now everything is working. Tests are passing.

    Source code(tar.gz)
    Source code(zip)
  • 0.1.5(Apr 8, 2015)

    • Created ViewSet routing and views
    • Use ViewSet by defualt
    • added argument to user APIView (--api-view)
    • Refactored to Generator class for easier extension
    • Refactored all commands to one command class, keep it DRY
    • Added example application
    • Added tests
    Source code(tar.gz)
    Source code(zip)
  • 0.1.4(Apr 7, 2015)

    Each command can now be run separately

    • generate-serializers
    • generate-views
    • generate-urls
    • generate-api

    Removed dependency on get_models method which is deprecated in Django 1.8.

    Source code(tar.gz)
    Source code(zip)
  • 0.1.3(Apr 7, 2015)

  • 0.1.2(Apr 7, 2015)

Owner
Tobin Brown
Software Developer at Applied Systems
Tobin Brown
Country-specific Django helpers, to use in Django Rest Framework

django-rest-localflavor Country-specific serializers fields, to Django Rest Framework Documentation (soon) The full documentation is at https://django

Gilson Filho 19 Aug 30, 2022
RESTler is the first stateful REST API fuzzing tool for automatically testing cloud services through their REST APIs and finding security and reliability bugs in these services.

RESTler is the first stateful REST API fuzzing tool for automatically testing cloud services through their REST APIs and finding security and reliability bugs in these services.

Microsoft 1.8k Jan 4, 2023
BloodDonors: Built using Django REST Framework for the API backend and React for the frontend

BloodDonors By Daniel Yuan, Alex Tian, Aaron Pan, Jennifer Yuan As the pandemic raged, one of the side effects was an urgent shortage of blood donatio

Daniel Yuan 1 Oct 24, 2021
Authentication for Django Rest Framework

Dj-Rest-Auth Drop-in API endpoints for handling authentication securely in Django Rest Framework. Works especially well with SPAs (e.g React, Vue, Ang

Michael 1.1k Dec 28, 2022
A JSON Web Token authentication plugin for the Django REST Framework.

Simple JWT Abstract Simple JWT is a JSON Web Token authentication plugin for the Django REST Framework. For full documentation, visit django-rest-fram

Jazzband 3.3k Jan 4, 2023
Automated generation of real Swagger/OpenAPI 2.0 schemas from Django REST Framework code.

drf-yasg - Yet another Swagger generator Generate real Swagger/OpenAPI 2.0 specifications from a Django Rest Framework API. Compatible with Django Res

Cristi Vîjdea 3k Jan 6, 2023
Introduction to Django Rest Framework

Introduction to Django Rest Framework This is the repository of the video series Introduction to Django Rest Framework published on YouTube. It is a s

Simple is Better Than Complex 20 Jul 14, 2022
JSON:API support for Django REST framework

JSON:API and Django REST framework Overview JSON:API support for Django REST framework Documentation: https://django-rest-framework-json-api.readthedo

null 1k Dec 27, 2022
DRF-extensions is a collection of custom extensions for Django REST Framework

Django REST Framework extensions DRF-extensions is a collection of custom extensions for Django REST Framework Full documentation for project is avail

Gennady Chibisov 1.3k Dec 28, 2022
Swagger Documentation Generator for Django REST Framework: deprecated

Django REST Swagger: deprecated (2019-06-04) This project is no longer being maintained. Please consider drf-yasg as an alternative/successor. I haven

Marc Gibbons 2.6k Dec 23, 2022
Document Web APIs made with Django Rest Framework

DRF Docs Document Web APIs made with Django Rest Framework. View Demo Contributors Wanted: Do you like this project? Using it? Let's make it better! S

Manos Konstantinidis 626 Nov 20, 2022
Recursive Serialization for Django REST framework

djangorestframework-recursive Overview Recursive Serialization for Django REST framework This package provides a RecursiveField that enables you to se

null 336 Dec 28, 2022
Dropdown population implementation for Django REST Framework

drf-dropdown Dropdown population implementation for Django REST Framework Usage Add DropdownView to API URL # urls.py import dropdown urlpatterns = [

Preeti Yuankrathok 4 Dec 6, 2022
simple api build with django rest framework

Django Rest API django-rest-framework Employees management simple API in this project wrote test suites for endpoints wrote simple doc string for clas

OMAR.A 1 Mar 31, 2022
Simple Crud Api With Django Rest Framework

SIMPLE CRUD API WITH DJANGO REST FRAMEWORK Django REST framework is a powerful and flexible toolkit for building Web APIs. Requirements Python 3.6 Dja

kibet hillary 1 May 3, 2022
Built on Django Rest Framework, to provide with command execution on linux terminal

Built on Django Rest Framework, to provide with command execution on linux terminal

null 1 Oct 31, 2021
Mlflow-rest-client - Python client for MLflow REST API

Python Client for MLflow Python client for MLflow REST API. Features: Minimal de

MTS 35 Dec 23, 2022
Example Starlette REST API application

The idea of this project is to show how Starlette, Marshmallow, and SQLAlchemy can be combined to create a RESTful HTTP API application that is modular, lightweight, and capable of dealing with many simultaneous requests.

Robert Wikman 0 Jan 7, 2022