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
A lightweight REST miniframework for Python.

restless A lightweight REST miniframework for Python. Documentation is at https://restless.readthedocs.io/. Works great with Django, Flask, Pyramid, T

Daniel Lindsley 824 Nov 20, 2022
A minimalistic manga reader for desktop built with React and Django

smanga A minimalistic manga reader/server for serving local manga images on desktop browser. Provides a two-page view layout just as reading a physica

Padam Upreti 13 Sep 24, 2022
Estudo e desenvolvimento de uma API REST

Estudo e desenvolvimento de uma API REST 🧑‍💻 Tecnologias Esse projeto utilizará as seguintes tecnologias: Git Python Flask DBeaver Vscode SQLite 🎯

Deusimar 7 May 30, 2022
Django REST API with React BoilerPlate

This is a setup of Authentication and Registration Integrated with React.js inside the Django Templates for web apps

Faisal Nazik 91 Dec 30, 2022
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 04, 2023
Flask RestAPI Project - Transimage Rest API For Python

[ 이미지 변환 플라스크 Rest API ver01 ] 0. Flask Rest API - in SunnyWeb : 이미지 변환 웹의 Flask

OliverKim 1 Jan 12, 2022
Creating delicious APIs for Django apps since 2010.

django-tastypie Creating delicious APIs for Django apps since 2010. Currently in beta but being used actively in production on several sites. Requirem

3.8k Dec 30, 2022
A small repository of projects built in my course, REST APIs with Flask and Python.

A small repository of projects built in my course, REST APIs with Flask and Python.

Teclado 1k Jan 05, 2023
REST implementation of Django authentication system.

djoser REST implementation of Django authentication system. djoser library provides a set of Django Rest Framework views to handle basic actions such

Sunscrapers 2.2k Jan 01, 2023
DSpace REST API Client Library

DSpace Python REST Client Library This client library allows Python 3 scripts (Python 2 probably compatible but not officially supported) to interact

The Library Code GmbH 10 Nov 21, 2022
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
Kong API Manager with Prometheus And Splunk

API Manager Stack Run Kong Server + Konga + Prometheus + Grafana + API & DDBB + Splunk Clone the proyect and run docker-compose up

Santiago Fernandez 82 Nov 26, 2022
BreakFastApi 🍣 🍔 🍕 The most delicious API on the web

BreakFastApi 🍣 🍔 🍕 The most delicious API on the web. Just send a request and you'll receive the most mouth watering dish recipe with estimated coo

Mariia Sizova 156 Nov 19, 2022
REST API with Flask. No data persistence.

Flask REST API Python 3.9.7 The Flask experience, without data persistence :D First, to install all dependencies: python -m pip install -r requirement

Luis Quiñones Requelme 1 Dec 15, 2021
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 04, 2023
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 06, 2022
FastAPI framework, high performance, easy to learn, fast to code, ready for production

FastAPI framework, high performance, easy to learn, fast to code, ready for production Documentation: https://fastapi.tiangolo.com Source Code: https:

Sebastián Ramírez 53.1k Jan 06, 2023
Little Library API REST

Little Library API REST py 3.10 The only one requeriment it's to have Flask installed.

Luis Quiñones Requelme 1 Dec 15, 2021
Async Python 3.6+ web server/framework | Build fast. Run fast.

Sanic | Build fast. Run fast. Build Docs Package Support Stats Sanic is a Python 3.6+ web server and web framework that's written to go fast. It allow

Sanic Community Organization 16.7k Dec 28, 2022