Skip to content

Generate Django RESTful APIs automatically from introspecting the database schema for PostgreSQL databases

License

Notifications You must be signed in to change notification settings

maheshbabugorantla/DBtoDRF

Repository files navigation

πŸš€ Generate Django RESTful API from a relational database schema

Python Django License PRs Welcome

Automatically generate a complete Django REST Framework API from your existing database schema using Django's powerful introspection capabilities.

Transform your database into a production-ready REST API in seconds, not hours. DRF Auto Generator analyzes your database schema and creates models, serializers, views, URLs, admin interfaces, and comprehensive API documentation - all with proper relationships, constraints, and best practices.


✨ Features

πŸ—οΈ Complete API Generation

  • Django Models with proper field types, relationships, and constraints
  • DRF Serializers with nested relationships and validation
  • ViewSets & Views with CRUD operations and filtering
  • URL Configuration with RESTful routing
  • Admin Interface with inline editing and search
  • OpenAPI Documentation with Swagger UI integration

🎯 Smart Database Analysis

  • Relationship Detection - Automatically identifies Foreign Keys, Many-to-Many, and One-to-One relationships
  • Constraint Mapping - Preserves unique constraints, indexes, and check constraints
  • Accurate Data Type Mapping - Maps database types to appropriate Django fields
  • Primary Key Handling - Supports simple and composite primary keys

πŸ› οΈ Database Support

Database Status Notes
PostgreSQL βœ… Full Support Recommended for production
MySQL/MariaDB πŸ”„ Planned Next Release
SQLite πŸ”„ Planned Right after MySQL support
SQL Server πŸ”„ Planned Future release
Oracle πŸ”„ Planned Future release

🚦 Quick Start

πŸš€ Quick Start with Simple Blog Demo

The easiest way to try DRF Auto Generator is with our pre-configured blog example:

  1. Install uv

    $ curl -LsSf https://astral.sh/uv/install.sh | sh
  2. Test the api generation tool

# Clone the repository (if you haven't already)
git clone https://github.com/maheshbabugorantla/DBtoDRF.git
cd DBtoDRF

# Setup the virtualenv for the project using uv
uv venv --python 3.12 .venv && source .venv/bin/activate

# Install the tool
make build_for_postgres

# Navigate to the simple blog example
cd examples/simple_blog

# Start PostgreSQL with sample blog data
docker-compose -f docker-compose.yml up -d --build

# Keep running the below command until the STATUS show the database as healthy
docker-compose -f docker-compose.yml ps
NAME                IMAGE                COMMAND                  SERVICE             CREATED             STATUS                    PORTS
simple_blog_db      postgres:17-alpine   "docker-entrypoint.s…"   postgres            17 minutes ago      Up 17 minutes (healthy)   0.0.0.0:5432->5432/tcp

# Wait for database to be ready (check with docker-compose ps)

# Generate the Django REST API
drf-generate -c simple_blog_db_config.yaml

# Navigate to generated project and run it
cd simple_blog_api
uv venv .venv && source .venv/bin/activate
(.venv) uv pip install -r requirements.txt
(.venv) python manage.py runserver 8000 # If there is already service running on port 8000. Please choose a different port

# Replace the port number if other than 8000
Navigate to http://127.0.0.1:8000/api/schema/swagger-ui/#/

πŸ“– Documentation

Configuration Options

Create a YAML configuration file with the following options:

# Database Configuration (Required)
databases:
  default:
    ENGINE: 'django.db.backends.postgresql'  # Database backend
    NAME: 'mydb'                            # Database name
    USER: 'user'                            # Database user
    PASSWORD: 'password'                    # Database password
    HOST: 'localhost'                       # Database host
    PORT: '5432'                           # Database port

# Output Configuration
output_dir: "./generated_api"              # Output directory
project_name: "myapi_django"               # Django project name
app_name: "api"                           # Django app name


exclude_tables:                           # Exclude these tables
  - django_migrations
  - django_admin_log
  - django_content_type
  - django_session
  - auth_group
  - auth_group_permissions
  - auth_user_user_permissions
  - authtoken_token
  - auth_permission
  - auth_user
  - auth_user_groups

# API Documentation
openapi_title: "My API"                   # API title
openapi_version: "1.0.0"                 # API version
openapi_description: "Generated API"      # API description
openapi_server_url: "http://localhost:8000/api/"  # Server URL

# Advanced Options
relation_style: "pk"                      # Relationship style (pk, link, nested)
add_whitenoise: false                     # Add WhiteNoise for static files
generate_schemathesis_tests: true         # Generate property-based tests

Command Line Options

drf-generate [OPTIONS]

Options:
  -c, --config PATH          Configuration file path (required)
  -v, --verbose              Enable verbose logging
  --no-color                 Disable colored logging output
  --help                     Show help message

Examples

PostgreSQL with Custom Schema

For your own database, create a configuration file:

# config-postgres.yaml
databases:
  default:
    ENGINE: 'django.db.backends.postgresql'
    NAME: 'your_database'
    USER: 'your_user'
    PASSWORD: 'your_password'
    HOST: 'localhost'
    PORT: '5432'

output_dir: "./my_api"
project_name: "my_api_django"
app_name: "api"

openapi_title: "My Database API"
openapi_description: "Auto-generated API from database schema"
# Generate API from your database
drf-generate -c config-postgres.yaml -v

πŸ›οΈ Generated Project Structure

my_api/
β”œβ”€β”€ manage.py                          # Django management script
β”œβ”€β”€ requirements.txt                   # Python dependencies
β”œβ”€β”€ .env                              # Environment variables template
β”œβ”€β”€ .gitignore                        # Git ignore rules
β”œβ”€β”€ openapi.yaml                      # OpenAPI specification
β”œβ”€β”€ my_api_django/                    # Django project
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ settings.py                   # Django settings
β”‚   β”œβ”€β”€ urls.py                       # Root URL configuration
β”‚   β”œβ”€β”€ wsgi.py                       # WSGI application
β”‚   └── asgi.py                       # ASGI application
└── api/                              # Django app
    β”œβ”€β”€ __init__.py
    β”œβ”€β”€ apps.py                       # App configuration
    β”œβ”€β”€ models.py                     # Django models
    β”œβ”€β”€ serializers.py                # DRF serializers
    β”œβ”€β”€ views.py                      # DRF views
    β”œβ”€β”€ urls.py                       # App URL configuration
    β”œβ”€β”€ admin.py                      # Django admin
    β”œβ”€β”€ migrations/                   # Database migrations
    β”‚   └── __init__.py
    └── tests/                        # Generated tests
        β”œβ”€β”€ __init__.py
        β”œβ”€β”€ test_schemathesis_integration.py  # Property-based API tests
        β”œβ”€β”€ test_api_users.py         # Per-model tests
        └── README.md                 # Testing documentation

⚑ Advanced Usage

Custom Field Mapping

The generator intelligently maps database types to Django fields:

Database Type Django Field Notes
varchar(n) CharField(max_length=n) Character fields
text TextField() Large text
integer IntegerField() Integers
bigint BigIntegerField() Large integers
decimal(p,s) DecimalField(max_digits=p, decimal_places=s) Precise decimals
boolean BooleanField() True/False
date DateField() Dates
timestamp DateTimeField() Date/time
json/jsonb JSONField() JSON data (PostgreSQL)

Relationship Handling

The generator automatically detects and creates:

  • Foreign Keys β†’ ForeignKey fields with proper on_delete behavior
  • Many-to-Many β†’ ManyToManyField with automatic through table detection
  • One-to-One β†’ OneToOneField relationships
  • Self-referential β†’ Self-referencing relationships with appropriate related_name

🀝 Contributing

We welcome contributions! Here's how to get started:

Development Setup

# Clone the repository
git clone https://github.com/maheshbabugorantla/drf-auto-generator.git
cd drf-auto-generator

# Create virtual environment
python -m venv .venv
source .venv/bin/activate  # On Windows: .venv\Scripts\activate

# Install development dependencies
pip install -e ".[dev]"

# Install pre-commit hooks
pre-commit install

Running Tests

# Run all tests
python -m pytest tests/ -v

# Run with coverage
python -m pytest tests/ --cov=drf_auto_generator --cov-report=html

# Run specific test categories
python -m pytest tests/test_models.py -v
python -m pytest tests/test_serializers.py -v
python -m pytest tests/test_views.py -v

Code Quality

# Format code
black drf_auto_generator/ tests/

# Lint code
ruff check drf_auto_generator/ tests/

# Type checking
mypy drf_auto_generator/

Contribution Guidelines

  1. Fork the repository and create a feature branch
  2. Write tests for new functionality
  3. Follow code style (Black formatting, type hints)
  4. Update documentation for new features
  5. Submit a Pull Request with a clear description

See CONTRIBUTING.md for detailed guidelines.


πŸ“„ License

This project is licensed under the Apache License 2.0 - see the LICENSE file for details.


πŸŽ‰ Acknowledgments

  • Django Team - For the amazing ORM and introspection capabilities
  • Django REST Framework - For the excellent API framework

🌟 Star History

Star History Chart


Made with ❀️ by Mahesh Babu Gorantla

About

Generate Django RESTful APIs automatically from introspecting the database schema for PostgreSQL databases

Resources

License

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages