my app structure is like this
/dose/
-----/api/
---------/atomicservice1.py
--------/atomicservice2.py
--------/atomicservice3.py
The contents of atomicservice1.py is…
from rest_framework.decorators import api_view
from rest_framework.response import Response
@api_view()
def hello_world(request):
return Response({“message”: “Hello, world!”})
Just for testing, I will flesh it out as I get it working.
do I need to create another urls.py under /api/ and include from /dose/urls.py?
Do you need to?
No. There’s no requirement that you do it that way.
However, it is the generally-accepted Django practice to keep your urls organized by Django app.
But, it’s certainly valid for you to include a specific url in your root urls.py file.
Ken,
Thanks, so I can add the URLPATTERN to my /dose/urls.py
The question remains what would the URLPATTERN for /dose/api/atomicservice1.py look like since it isn’t inside the views.py?
Assume for the moment that your hello_world view was in views.py.
What would your url definition for it look like?
Ok fair enough.
I tried
path(‘/api/’, views.hello_world.as_view())
I tried moving
@api_view()
def hello_world(request):
return Response({“message”: “Hello, world!”})
to my /dose/views.py
and setting path(‘/api/’, views.hello_world.as_view()),
but got path(‘/api/’, views.hello_world.as_view()),
AttributeError: ‘function’ object has no attribute ‘as_view’
]
Real progress.
Changed the APIView to
class myhello_world(APIView):
#@api_view()
def get(self, request, format=None):
return Response({“message”: “Hello, world!”})
and got
HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { “message”: “Hello, world!” }
So how do I move this to the one file per service structure I described in my original question?
Ok thanks Ken, with minimal hand holding and hints, I arrived at the solution.
in my /dose/urls.py
from .api.atomicservice1 import service1
from .api.atomicservice2 import service2
from .api.atomicservice3 import service3
in URLPATTERNS
path(‘api/atomicservice1/’, service1.as_view()),
path(‘api/atomicservice2/’, service2.as_view()),
path(‘api/atomicservice3/’, service3.as_view()),
and all is well.
1 Like