Break api.py
file into several for readability
#471
-
I need to create the CRUD api endpoints for over 20 models. e.g. How would I create a multiple api files while still using the single api object? Per the docs - one creates an from ninja import NinjaAPI
api = NinjaAPI()
@api.get("/hello")
def hello(request):
return "Hello world" and in from django.contrib import admin
from django.urls import path
from .api import api
urlpatterns = [
path("admin/", admin.site.urls),
path("api/", api.urls),
] I want to turn from ninja import NinjaAPI
api = NinjaAPI()
@api.get("/hello")
def hello(request):
return "Hello world" AND
@api.get("/hi-you-there")
def hello_class_b(request):
return "Hi You Are In Class B" currently if I try that - the 'hello' endpoint is showing but the hello_class_b is not. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
That should work fine, as long as each module actually gets imported before You could either do these imports on the urlconf ( Or you could import every split module class from |
Beta Was this translation helpful? Give feedback.
-
To expand for prosperity: This works: in from . import api_class_b.py
from .api_class_a import api # django_ninja api object in from .api_class_a import api
@api.get("/hi-you-there")
def hello_class_b(request):
return "Hi You Are In Class B" in from ninja import NinjaAPI
api = NinjaAPI()
@api.get("/hello")
def hello(request):
return "Hello **world"** |
Beta Was this translation helpful? Give feedback.
That should work fine, as long as each module actually gets imported before
api.urls
is called. Otherwise the decorators adding your functions to the api will never be executed!You could either do these imports on the urlconf (
import .api.api_class_b
)Or you could import every split module class from
api/__init__.py
. If you do that though, you'll want to put the actualapi = NinjaAPI()
in a child module rather than in the init root itself to avoid a circular import.