Auto-generate TypeScript clients for Django Ninja during runserver
Project description
Django Ninja TS Generator
Automatically builds your TypeScript client whenever your Django Ninja schema changes.
Installation
-
Install the package:
pip install django-ninja-ts
-
Add to
INSTALLED_APPSinsettings.py:INSTALLED_APPS = [ # ... 'django.contrib.staticfiles', 'django_ninja_ts', # Add this # ... ]
Requirements
This package requires the following external dependencies:
- Node.js (for
npx) - Java JRE (for OpenAPI Generator)
The package will provide installation instructions if these are missing.
Configuration
Add these settings to your settings.py:
import os
# Path to your NinjaAPI instance (dot notation)
NINJA_TS_API = 'myproject.api.api'
# Where to output the generated client
NINJA_TS_OUTPUT_DIR = os.path.join(BASE_DIR, '../frontend/src/app/shared/api')
# Optional: Debounce time in seconds (prevents rapid rebuilds on "Save All")
# Default: 1.0
NINJA_TS_DEBOUNCE_SECONDS = 0.5
# Optional: Override generator arguments
# Default: ['generate', '-g', 'typescript-fetch', '-p', 'removeOperationIdPrefix=true']
# NINJA_TS_CMD_ARGS = ['generate', '-g', 'typescript-axios']
How It Works
- When you run
python manage.py runserver, the package intercepts the command - It loads your Django Ninja API and extracts the OpenAPI schema
- It calculates a hash of the schema and compares it to the previous build
- If the schema has changed, it runs
openapi-generator-clivianpxto generate the TypeScript client - The hash is stored in
.schema.hashin the output directory to avoid unnecessary rebuilds
Configuration Options
| Setting | Required | Default | Description |
|---|---|---|---|
NINJA_TS_API |
Yes | - | Dot-notation path to your NinjaAPI instance |
NINJA_TS_OUTPUT_DIR |
Yes | - | Directory where the TypeScript client will be generated |
NINJA_TS_DEBOUNCE_SECONDS |
No | 1.0 |
Delay before generation to handle rapid file saves |
NINJA_TS_CMD_ARGS |
No | See below | Arguments passed to openapi-generator-cli |
Default Generator Arguments
['generate', '-g', 'typescript-fetch', '-p', 'removeOperationIdPrefix=true']
Example: Using Axios
NINJA_TS_CMD_ARGS = ['generate', '-g', 'typescript-axios']
Example: Using Angular
NINJA_TS_CMD_ARGS = ['generate', '-g', 'typescript-angular', '-p', 'removeOperationIdPrefix=true']
Logging
The package uses Python's standard logging module. To see debug output, configure logging in your settings:
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'class': 'logging.StreamHandler',
},
},
'loggers': {
'django_ninja_ts': {
'handlers': ['console'],
'level': 'DEBUG',
},
},
}
Troubleshooting
Common Issues
"Module not found" error
Problem: You see an error like Generation Error: Module not found: No module named 'myapp'
Solution: Ensure NINJA_TS_API contains a valid import path to your NinjaAPI instance:
# Correct - full import path
NINJA_TS_API = 'myapp.api.api'
# Incorrect - missing module path
NINJA_TS_API = 'api'
"does not have 'get_openapi_schema' method" error
Problem: The object at your NINJA_TS_API path is not a NinjaAPI instance.
Solution: Ensure you're pointing to the actual NinjaAPI instance, not a module or router:
# In myapp/api.py
from ninja import NinjaAPI
api = NinjaAPI() # This is what NINJA_TS_API should point to
# In settings.py
NINJA_TS_API = 'myapp.api.api' # Points to the 'api' variable in myapp/api.py
"Invalid OpenAPI schema" error
Problem: The schema returned by your API is missing required OpenAPI fields.
Solution: This usually indicates a configuration issue with your NinjaAPI. Ensure your API has:
- A title (set in NinjaAPI constructor or via
titleparameter) - At least one endpoint registered
api = NinjaAPI(title="My API", version="1.0.0")
@api.get("/health")
def health(request):
return {"status": "ok"}
Generation hangs indefinitely
Problem: The TypeScript generation process never completes.
Solution: The package has a 120-second timeout by default. If generation regularly times out:
- Check that Java and Node.js are properly installed
- Try running
npx openapi-generator-cli generate --helpmanually - Check for network issues (first run downloads the generator)
"Output directory parent is not writable" error
Problem: The package cannot create files in the specified output directory.
Solution: Ensure the parent directory of NINJA_TS_OUTPUT_DIR exists and has write permissions:
# Check permissions
ls -la /path/to/parent/directory
# Fix permissions if needed
chmod 755 /path/to/parent/directory
Schema not regenerating after changes
Problem: You've made API changes but the TypeScript client isn't updating.
Solution:
- Delete the
.schema.hashfile in your output directory - Restart the development server
- If using
NINJA_TS_DEBOUNCE_SECONDS, wait for the debounce period
Windows-specific issues
Problem: Commands fail on Windows with shell-related errors.
Solution: The package automatically uses shell=True on Windows for npx compatibility. If you still have issues:
- Ensure Node.js is in your PATH
- Try running from PowerShell instead of Command Prompt
- Run
npx openapi-generator-climanually to verify setup
Configuration Validation
The package validates your configuration at startup using Django's system checks. Run checks manually with:
python manage.py check
This will report any configuration errors like:
- Missing required settings
- Invalid setting types
- Unwritable output directories
Debug Mode
Enable debug logging to see detailed information about the generation process:
LOGGING = {
'version': 1,
'loggers': {
'django_ninja_ts': {
'handlers': ['console'],
'level': 'DEBUG',
},
},
}
Supported OpenAPI Generator Versions
This package works with any version of @openapitools/openapi-generator-cli available via npm. The generator is automatically downloaded on first use.
Contributing
Commit Messages
This project uses Conventional Commits for commit messages.
Format: <type>(<scope>): <description>
Types:
feat- New featuresfix- Bug fixesdocs- Documentation changesstyle- Code style changes (formatting, whitespace)refactor- Code refactoring without feature changestest- Adding or updating testschore- Maintenance tasks, dependencies, configs
Examples:
feat(generator): add support for axios client
fix(runserver): handle missing Java dependency gracefully
docs(readme): add troubleshooting section
License
MIT License - see LICENSE for details.
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file django_ninja_ts-1.0.0.tar.gz.
File metadata
- Download URL: django_ninja_ts-1.0.0.tar.gz
- Upload date:
- Size: 17.1 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
f733be4656bf455c6a379125499cbbf8a3f3de640fddd5aa45d49d349ee64804
|
|
| MD5 |
2e6fe3364d27f4cd719b542b33927e31
|
|
| BLAKE2b-256 |
f8fbd8fb29d049133ddbba76daa82808875060973e4c8e8dfc1dc6518dbdcb03
|
File details
Details for the file django_ninja_ts-1.0.0-py3-none-any.whl.
File metadata
- Download URL: django_ninja_ts-1.0.0-py3-none-any.whl
- Upload date:
- Size: 11.3 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
1896e39f59bcbd6d07b7ddffec1eeca4602942758c85be5b4cbe13391ca86276
|
|
| MD5 |
0a3dba874ed41d27f0f1c6089e550f8e
|
|
| BLAKE2b-256 |
f9a3b0b0c5e9e97655da936ebe25c4c59d132fef62fe228958219289d10aa721
|