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
Python bindings for Podman's RESTful API

podman-py This python package is a library of bindings to use the RESTful API of Podman. It is currently under development and contributors are welcom

Containers 142 Jan 06, 2023
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
Key-Value база данных на Tarantool и REST API к ней.

KVmail Key-Value база данных на Tarantool и REST API к ней. Документация к API доступна здесь. Requiremrnts ubuntu 16.04+ python3.6+ supervisord nginx

1 Jun 16, 2021
Django app for handling the server headers required for Cross-Origin Resource Sharing (CORS)

django-cors-headers A Django App that adds Cross-Origin Resource Sharing (CORS) headers to responses. This allows in-browser requests to your Django a

Adam Johnson 4.8k Jan 05, 2023
Simplified REST API to get stickers from Snap

Snap Sticker kit REST API Simplified REST API to get stickers from Snap 💻 Instructions Search stickers Request: url = "https://sticker-kit-horizon733

Dishant Gandhi 1 Jan 05, 2022
Restful API framework wrapped around MongoEngine

Flask-MongoRest A Restful API framework wrapped around MongoEngine. Setup from flask import Flask from flask_mongoengine import MongoEngine from flask

Close 525 Jan 01, 2023
Flask RestAPI Project - Transimage Rest API For Python

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

OliverKim 1 Jan 12, 2022
Automatically generate a RESTful API service for your legacy database. No code required!

sandman2 sandman2 documentation [ ~ Dependencies scanned by PyUp.io ~ ] sandman2 automagically generates a RESTful API service from your existing data

Jeff Knupp 1.9k Jan 07, 2023
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
The Web API toolkit. 🛠

🛠 The Web API toolkit. 🛠 Community: https://discuss.apistar.org 🤔 💭 🤓 💬 😎 Documentation: https://docs.apistar.com 📘 Requirements: Python 3.6+

Encode 5.6k Dec 27, 2022
Integrate GraphQL into your Django project.

Graphene-Django A Django integration for Graphene. 💬 Join the community on Slack Documentation Visit the documentation to get started! Quickstart For

GraphQL Python 4k Dec 31, 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
Django Ninja is a web framework for building APIs with Django and Python 3.6+ type hints.

💨 Fast, Async-ready, Openapi, type hints based framework for building APIs

Vitaliy Kucheryaviy 3.8k Jan 04, 2023
a web-remote minecraft server wrapper with some unique features

Canceled here, continued as Semoxy MCWeb - a Minecraft Server Web Interface MCWeb is a web-remote Minecraft Server Wrapper for controlling your Minecr

Anton Vogelsang 1 Jul 12, 2021
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
Browsable web APIs for Flask.

Flask API Browsable web APIs for Flask. Status: This project is in maintenance mode. The original author (Tom Christie) has shifted his focus to API S

Flask API 1.3k Dec 27, 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
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
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

1k Dec 27, 2022
Extensions for Django REST Framework

Extensions for Django REST Framework

aiden 6 Dec 27, 2022